Skip to content

Commit

Permalink
Work String#starts_with? with regex (#5485)
Browse files Browse the repository at this point in the history
* Work String#starts_with? with regex

This feature is imported from Ruby 2.5.0.

See: https://bugs.ruby-lang.org/issues/13712

* Fix String#ends_with to accept regex

See: #5485 (comment)
  • Loading branch information
makenowjust authored and RX14 committed Apr 9, 2018
1 parent 3138b52 commit 4f4240b
Show file tree
Hide file tree
Showing 2 changed files with 12 additions and 0 deletions.
4 changes: 4 additions & 0 deletions spec/std/string_spec.cr
Original file line number Diff line number Diff line change
Expand Up @@ -945,6 +945,8 @@ describe "String" do
it { "foobar".starts_with?("").should be_true }
it { "foobar".starts_with?("foobarbaz").should be_false }
it { "foobar".starts_with?("foox").should be_false }
it { "foobar".starts_with?(/foo/).should be_true }
it { "foobar".starts_with?(/bar/).should be_false }
it { "foobar".starts_with?('f').should be_true }
it { "foobar".starts_with?('g').should be_false }
it { "よし".starts_with?('よ').should be_true }
Expand All @@ -956,6 +958,8 @@ describe "String" do
it { "foobar".ends_with?("").should be_true }
it { "foobar".ends_with?("foobarbaz").should be_false }
it { "foobar".ends_with?("xbar").should be_false }
it { "foobar".ends_with?(/bar/).should be_true }
it { "foobar".ends_with?(/foo|baz/).should be_false }
it { "foobar".ends_with?('r').should be_true }
it { "foobar".ends_with?('x').should be_false }
it { "よし".ends_with?('し').should be_true }
Expand Down
8 changes: 8 additions & 0 deletions src/string.cr
Original file line number Diff line number Diff line change
Expand Up @@ -4020,6 +4020,10 @@ class String
false
end

def starts_with?(re : Regex)
!!($~ = re.match_at_byte_index(self, 0, Regex::Options::ANCHORED))
end

def ends_with?(str : String)
return false if str.bytesize > bytesize
(to_unsafe + bytesize - str.bytesize).memcmp(str.to_unsafe, str.bytesize) == 0
Expand All @@ -4042,6 +4046,10 @@ class String
true
end

def ends_with?(re : Regex)
!!($~ = /#{re}\z/.match(self))
end

# Interpolates *other* into the string using `Kernel#sprintf`.
#
# ```
Expand Down

0 comments on commit 4f4240b

Please sign in to comment.