Matt Huggins Matt Huggins - 10 months ago 70
Ruby Question

Ruby gsub with index/offset?

Does Ruby's String#gsub method provide a means for including the index of the replacement? For example, given the following string:

I like you, you, you, and you.

I want to end up with this output:

I like you1, you2, you3, and you4.

I know I can use
, etc. for matching characters in parentheses, but is there anything like
that would provide the number of the current match?

It's worth mentioning that my actual term is not as simple as "you", so an alternate approach that assumes the search term is static will not suffice.

Answer Source

We can chain with_index to gsub() to get:

foo = 'I like you, you, you, and you.'.gsub(/\byou\b/).with_index { |m, i| "#{m}#{1+i}" }
puts foo

which outputs:

I like you1, you2, you3, and you4.