[ruby] Replace words in a string - Ruby

I have a string in Ruby:

sentence = "My name is Robert"

How can I replace any one word in this sentence easily without using complex code or a loop?

This question is related to ruby ruby-on-rails-3

The answer is


If you're dealing with natural language text and need to replace a word, not just part of a string, you have to add a pinch of regular expressions to your gsub as a plain text substitution can lead to disastrous results:

'mislocated cat, vindicating'.gsub('cat', 'dog')
=> "mislodoged dog, vindidoging"

Regular expressions have word boundaries, such as \b which matches start or end of a word. Thus,

'mislocated cat, vindicating'.gsub(/\bcat\b/, 'dog')
=> "mislocated dog, vindicating"

In Ruby, unlike some other languages like Javascript, word boundaries are UTF-8-compatible, so you can use it for languages with non-Latin or extended Latin alphabets:

'???? ? ??????, ??? ??????'.gsub(/\b????\b/, '?????')
=> "????? ? ??????, ??? ??????"

sentence.sub! 'Robert', 'Joe'

Won't cause an exception if the replaced word isn't in the sentence (the []= variant will).

How to replace all instances?

The above replaces only the first instance of "Robert".

To replace all instances use gsub/gsub! (ie. "global substitution"):

sentence.gsub! 'Robert', 'Joe'

The above will replace all instances of Robert with Joe.


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").