all jazz
all jazz

Reputation: 2017

looping through scan and replacing matches individually

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

Upvotes: 7

Views: 1662

Answers (2)

Peter Alfvin
Peter Alfvin

Reputation: 29419

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.

Upvotes: 6

BWStearns
BWStearns

Reputation: 2706

If you're looking for the same thing every time then you could just do:

def some_function_here(args)
    .... some logic creates replacement
    while something == true
        content.sub(/myregex/, replacement)
        .... some logic to change replacement/or a call to a helper function
    end
end

Not sure how you're generating the new replacement values, but from what I gather it appears that the easiest way to do it is to call the sub method on the string for your regex and replace them one at a time.

Upvotes: 0

Related Questions