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

RubyStringReplace

Ruby Problem Overview


a = "foobarfoobarhmm"

I want the output as `"fooBARfoobarhmm"

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

Ruby Solutions


Solution 1 - Ruby

Use #sub:

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

Solution 2 - Ruby

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

Solution 3 - Ruby

to replace the first occurrence, just do this:

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'

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionSayujView Question on Stackoverflow
Solution 1 - RubyYossiView Answer on Stackoverflow
Solution 2 - RubytbuehlmannView Answer on Stackoverflow
Solution 3 - RubyNafaa BouteferView Answer on Stackoverflow