Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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 \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.

like image 510
Matt Huggins Avatar asked Aug 30 '12 15:08

Matt Huggins


3 Answers

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.
like image 117
the Tin Man Avatar answered Oct 01 '22 01:10

the Tin Man


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."
like image 38
apneadiving Avatar answered Oct 01 '22 03:10

apneadiving


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.
like image 30
Dan McClain Avatar answered Oct 01 '22 03:10

Dan McClain