Ruby - replace the first occurrence of a substring

2019-01-22 17:03发布

问题:

a = "foobarfoobarhmm"

I want the output as `"fooBARfoobarhmm"

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

回答1:

Use #sub:

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


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


回答3:

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'