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

a = "foobarfoobarhmm"

I want the result to be like "fooBARfoobarhmm"

that is, only the first appearance of "bar" should be replaced by "BAR".

+45
string ruby replace
Nov 01. '11 at 7:01
source share
3 answers

Use #sub :

 a.sub('bar', "BAR") 
+82
Nov 01 2018-11-11T00:
source share

String#sub is what you need, as Yossi said. But instead, I would use Regexp, as it is faster:

 a = 'foobarfoobarhmm' output = a.sub(/foo/, 'BAR') 
+10
Nov 01 2018-11-11T00:
source share

to replace the first occurrence, simply do the following:

 str = "Hello World" str['Hello'] = 'Goodbye' # the result is 'Goodbye World' 

you can even use regular expressions:

 str = "I have 20 dollars" str[/\d+/] = 500.to_s # will give 'I have 500 dollars' 
+4
May 12 '14 at 4:32
source share



All Articles