Block with Regexp#match


(George Ogata) #1

Since Regexp#match so far does not use a block, why not extend it to
iterate over all the (non-overlapping) matches in the string? I think
the following sums up what I mean:

···

class Regexp
def match(str)
if block_given?
str.gsub!(self) {|s| yield $~; s}
self
else
old_match(str) # the current Regexp#match
end
end
end

/<(.*?)>/.match(’’) {|m| puts m[1]}

…seems pretty intuitive to me.

Is this a bad idea?


(David Alan Black) #2

Hello –

···

On Thu, 4 Jul 2002, George Ogata wrote:

Since Regexp#match so far does not use a block, why not extend it to
iterate over all the (non-overlapping) matches in the string? I think
the following sums up what I mean:


class Regexp
def match(str)
if block_given?
str.gsub!(self) {|s| yield $~; s}
self
else
old_match(str) # the current Regexp#match
end
end
end

/<(.*?)>/.match(’’) {|m| puts m[1]}

…seems pretty intuitive to me.

I think String#scan would do what you want:

‘’.scan(/<(.*?)>/)

(with or without block – see docs)

David


David Alan Black
home: dblack@candle.superlink.net
work: blackdav@shu.edu
Web: http://pirate.shu.edu/~blackdav