Skip to content

Instantly share code, notes, and snippets.

@sw17ch
Created August 10, 2012 14:54
Show Gist options
  • Save sw17ch/3314771 to your computer and use it in GitHub Desktop.
Save sw17ch/3314771 to your computer and use it in GitHub Desktop.
String#match_all :: Like String#scan but returns array of MatchData objects instead.
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
match_datas = []
while match_str.length > 0 do
md = match_str.match(regex)
break unless md
match_datas << md
match_str = md.post_match
end
return match_datas
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
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment