Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Ruby - replace the first occurrence of a substring with another string

a = "foobarfoobarhmm"

I want the output as `"fooBARfoobarhmm"

ie only the first occurrence of "bar" should be replaced with "BAR".

like image 999
Sayuj Avatar asked Nov 01 '11 07:11

Sayuj


People also ask

How do you replace a string with another string in Ruby?

Ruby allows part of a string to be modified through the use of the []= method. To use this method, simply pass through the string of characters to be replaced to the method and assign the new string.

How do you use Replace in Ruby?

First, you don't declare the type in Ruby, so you don't need the first string . To replace a word in string, you do: sentence. gsub(/match/, "replacement") .

How do you replace multiple characters in a string in Ruby?

Since Ruby 1.9. 2, String#gsub accepts hash as a second parameter for replacement with matched keys. You can use a regular expression to match the substring that needs to be replaced and pass hash for values to be replaced.


2 Answers

Use #sub:

a.sub('bar', "BAR") 
like image 52
Yossi Avatar answered Sep 18 '22 14:09

Yossi


String#sub is what you need, as Yossi already said. But I'd use a Regexp instead, since it's faster:

a = 'foobarfoobarhmm' output = a.sub(/foo/, 'BAR') 
like image 42
tbuehlmann Avatar answered Sep 20 '22 14:09

tbuehlmann