class String
def each_match(pattern, &block)
return Enumerator.new(self, :each_match, pattern) unless block_given?
text = self
m = text.match(pattern)
while m
yield m
text = text[m.end(0)..-1]
m = text.match(pattern)
end
end
end
Thank you for a solution! I always forgot about regexp global vars. Though I suggest that using a special method here is more clear. So what'd you say about String#each_match and Regexp#each_match
Yes, implementation is as simple as
class String
def each_match(pat)
scan(pat){ yield $~ }
end
end
and similar for Regexp.
Eregon (Benoit Daloze) wrote:
=begin
You can use (({String#scan})) with the block form and (({$~})) (as well as other Regexp-related globals) for this:
Though I suggest that using a special method here is more clear.
So what'd you say about String#each_match and Regexp#each_match
I did indeed somewhat expected String#scan to yield a MatchData object, instead of $~.captures.
I'm in favor of String#each_match, it might be a nice addition and the name is clear, but the naming is different from the usual regexp methods on String, and it might not be worth to add a method (I agree $~ is not the prettiest thing around).
I think Regexp#each_match does not convey well what it does though.