Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to replace the last occurrence of a substring in ruby?

Tags:

ruby

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?

like image 919
Just a learner Avatar asked Jul 06 '10 09:07

Just a learner


People also ask

How do you replace a substring in Ruby?

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!

How do you replace a word in an array in Ruby?

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.

How do you find the substring of a string in Ruby?

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.


2 Answers

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" 
like image 115
Chowlett Avatar answered Sep 22 '22 23:09

Chowlett


"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" 
like image 41
Mladen Jablanović Avatar answered Sep 22 '22 23:09

Mladen Jablanović