Block form of gsub - passing backreferences to parsing functions 1
def hello(message)
"#{messsage}!"
end
"1234foo4567foo".gsub /(\d*)foo/, hello($1)
=> "!!"
"1234foo4567foo".gsub /(\d*)foo/, hello($1)
=> "4567!4567!"
I needed to pass a backreference ($1 or \1) from a regexp into a parsing method and then replace the match with the result. I tried many ways and couldn’t quite figure out why I couldn’t do it, before realizing that the $n variables get populated based on the last match, so won’t be populated when passed into the method call in the substitution param, or will be populated from the last time it was run. And the ’\1’ for won’t work for similar, if slightly different reasons.
Then I discovered the block form of gsub, which passes in each match to the block, and populates all the relevant regexp backreference/match globals:
"1234foo4567foo".gsub(/(\d*)foo/){|m| hello($1)}
=> "1234!4567!"

Articles via rss or email
This is just what I was looking for. Thanks! I was pulling my hair trying to figure out how to do the replacements.