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 \1
, \2
, etc. for matching characters in parentheses, but is there anything like \i
or \n
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.
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.
This works but it's ugly:
n = 0;
"I like you, you, you, and you.".gsub("you") { val = "you" + n.to_s; n+=1; val }
=> "I like you0, you1, you2, and you3."
This is a little bit hacky, but you can use a variable that you increment inside of a block passed into gsub
source = 'I like you, you, you, and you.'
counter = 1
result = source.gsub(/you/) do |match|
res = "#{match}#{counter}"
counter += 1
res
end
puts result
#=> I like you1, you2, you3, and you4.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With