a = "foobarfoobarhmm"
I want the output as `"fooBARfoobarhmm"
ie only the first occurrence of "bar" should be replaced with "BAR".
Ruby allows part of a string to be modified through the use of the []= method. To use this method, simply pass through the string of characters to be replaced to the method and assign the new string.
First, you don't declare the type in Ruby, so you don't need the first string . To replace a word in string, you do: sentence. gsub(/match/, "replacement") .
Since Ruby 1.9. 2, String#gsub accepts hash as a second parameter for replacement with matched keys. You can use a regular expression to match the substring that needs to be replaced and pass hash for values to be replaced.
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')
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With