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

Solution 1:

Use #sub:

a.sub('bar', "BAR")

Solution 2:

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')