Is there a way to pass a regex capture to a block in Ruby?

Posted by Gordon Fontenot on Stack Overflow See other posts from Stack Overflow or by Gordon Fontenot
Published on 2011-01-17T23:31:35Z Indexed on 2011/01/18 0:53 UTC
Read the original article Hit count: 159

Filed under:
|
|

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)?

© Stack Overflow or respective owner

Related posts about ruby

Related posts about regex