Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

looping through scan and replacing matches individually

Tags:

regex

ruby

I would like to loop through regex matches and replace each match individually in the loop.

For example:

content.scan(/myregex/).each do |m|
  m = 'new str'
end

How could I do that?

The reason why I want to do that is because each match will be replaced with a different output from a function.

Thanks for help

like image 978
all jazz Avatar asked Sep 20 '13 00:09

all jazz


1 Answers

The following form of the gsub method will do exactly what you want:

gsub(pattern) {|match| block } → new_str

See http://ruby-doc.org/core-2.0.0/String.html#method-i-gsub for documentation.

like image 158
Peter Alfvin Avatar answered Sep 26 '22 07:09

Peter Alfvin