71

a = "foobarfoobarhmm"

I want the output as `"fooBARfoobarhmm"

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

3 Answers 3

135

Use #sub:

a.sub('bar', "BAR")
Sign up to request clarification or add additional context in comments.

Comments

18

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

7 Comments

I just did a benchmark and regex takes 50% longer than just using a string as parameter for sub.
I checked it, and the Regexp version is faster. I used MRI 1.9.2, 1.9.3, 2.0.0 and even JRuby, all of them being faster on the Regexp version. The benchmark code: gist.github.com/tbuehlmann/5574713 Wanna provide your benchmark?
That's not very intuitive. I would expect a regex to be slower than a specialised method.
In my opinion (IMO), when you don't need a regex, the string version is more readable.
@NielsB. RegEx engines vary greatly on their level of optimization. String parsing has a wide spectrum of efficiency from horrible to impressive. RegEx can be on both ends.
|
11

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'

2 Comments

500.to_s is sometimes written "500". :-)
I wrote it like that intentionally. to indicate that you need to assign an explicit string. Because the conversion is not automatic here. If you do this instead str[/\d+/] = 500 you'll get an error TypeError: no implicit conversion of Fixnum into String .

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.