I want to replace the last occurrence of a substring in Ruby. What's the easiest way? For example, in abc123abc123, I want to replace the last abc to ABC. How do I do that?
Ruby String SubstitutionThe gsub and gsub! methods provide another quick and easy way of replacing a substring with another string. These methods take two arguments, the search string and the replacement string. The gsub method returns a modified string, leaving the original string unchanged, whereas the gsub!
Ruby | Array replace() function Array#replace() : replace() is a Array class method which returns an array of all combinations of elements from all arrays. Return: an array of all combinations of elements from all arrays.
There is no substring method in Ruby, and hence we rely upon ranges and expressions. If we want to use the range, we have to use periods between the starting and ending index of the substring to get a new substring from the main string.
How about
new_str = old_str.reverse.sub(pattern.reverse, replacement.reverse).reverse
For instance:
irb(main):001:0> old_str = "abc123abc123" => "abc123abc123" irb(main):002:0> pattern="abc" => "abc" irb(main):003:0> replacement="ABC" => "ABC" irb(main):004:0> new_str = old_str.reverse.sub(pattern.reverse, replacement.reverse).reverse => "abc123ABC123"
"abc123abc123".gsub(/(.*(abc.*)*)(abc)(.*)/, '\1ABC\4') #=> "abc123ABC123"
But probably there is a better way...
Edit:
...which Chris kindly provided in the comment below.
So, as *
is a greedy operator, the following is enough:
"abc123abc123".gsub(/(.*)(abc)(.*)/, '\1ABC\3') #=> "abc123ABC123"
Edit2:
There is also a solution which neatly illustrates parallel array assignment in Ruby:
*a, b = "abc123abc123".split('abc', -1) a.join('abc')+'ABC'+b #=> "abc123ABC123"
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