Skip to content

Commit 478f9bb

Browse files
committed
Fixes a bug in Stringends_with?
iex> String.ends_with? "hello", ["hell", "lo"] false The problem was that the implementation uses :binary.matches, and that returns only one match. It would find "hell", but pos+len != size, and so returned false. Changed for a less efficient implementation.
1 parent c3dd400 commit 478f9bb

File tree

2 files changed

+10
-4
lines changed

2 files changed

+10
-4
lines changed

lib/elixir/lib/string.ex

Lines changed: 9 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -835,10 +835,15 @@ defmodule String do
835835
"""
836836
@spec ends_with?(t, t | [t]) :: boolean
837837

838-
def ends_with?(string, suffixes) do
839-
string_size = size(string)
840-
matches = :binary.matches(string, suffixes)
841-
Enum.any? matches, fn({pos, len})-> pos + len == string_size end
838+
def ends_with?(string, suffixes) when is_list(suffixes) do
839+
string_len = String.length(string)
840+
Enum.any? suffixes,
841+
fn suffix ->
842+
len = String.length(suffix)
843+
suffix == String.slice(string, string_len - len, len)
844+
end
842845
end
843846

847+
def ends_with?(string, suffix), do: __MODULE__.ends_with?(string, [ suffix ])
848+
844849
end

lib/elixir/test/elixir/string_test.exs

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -294,6 +294,7 @@ defmodule StringTest do
294294
test :ends_with? do
295295
assert String.ends_with? "hello", "lo"
296296
assert String.ends_with? "hello", "hello"
297+
assert String.ends_with? "hello", ["hell", "lo", "xx"]
297298
assert String.ends_with? "hello", ["hellö", "lo"]
298299
assert String.ends_with? "エリクシア", "シア"
299300
refute String.ends_with? "hello", "he"

0 commit comments

Comments
 (0)