简体   繁体   中英

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.

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM