Skip to content

Instantly share code, notes, and snippets.

@zdennis
Forked from sw17ch/match_all.rb
Created August 10, 2012 15:24
Show Gist options
  • Save zdennis/3314998 to your computer and use it in GitHub Desktop.
Save zdennis/3314998 to your computer and use it in GitHub Desktop.
String#match_all :: Like String#scan but returns array of MatchData objects instead. (ruby 1.9-ified)
class String
# This method will return an array of MatchData's rather than the
# array of strings returned by the vanilla `scan`.
def match_all(regex)
match_str = self
[].tap do |match_datas|
while md = match_str.match(regex)
match_datas << md
match_str = md.post_match
end
end
end
end
describe String do
describe :match_all do
it "it works like scan, but uses MatchData objects instead of arrays and strings" do
mds = "ABC-123, DEF-456, GHI-098".match_all(/(?<word>[A-Z]+)-(?<number>[0-9]+)/)
mds[0][:word].should == "ABC"
mds[0][:number].should == "123"
mds[1][:word].should == "DEF"
mds[1][:number].should == "456"
mds[2][:word].should == "GHI"
mds[2][:number].should == "098"
end
end
end
@andriimosin
Copy link

Thanks! This helped me a lot!

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment