Created
August 10, 2012 14:54
-
-
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.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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 |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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