Is there a way to pass a regex capture to a block in Ruby?
- by Gordon Fontenot
I have a hash with a regex for the key and a block for the value. Something like the following:
{ 'test (.+?)' => { puts $1 } }
Not exactly like that, obviously, since the block is being stored as a Proc, but that's the idea.
I then have a regex match later on that looks a lot like this
hash.each do |pattern, action|
if /#{pattern}/i.match(string)
action.call
end
end
The idea was to store the block away in the hash to make it a bit easier for me to expand upon in the future, but now the regex capture doesn't get passed to the block. Is there a way to do this cleanly that would support any number of captures I put in the regex (as in, some regex patterns may have 1 capture, others may have 3)?