a = "foobarfoobarhmm"
I want the output as `"fooBARfoobarhmm"
ie only the first occurrence of "bar" should be replaced with "BAR".
a = "foobarfoobarhmm"
I want the output as `"fooBARfoobarhmm"
ie only the first occurrence of "bar" should be replaced with "BAR".
Use #sub
:
a.sub('bar', "BAR")
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')
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'