OneBite.Dev - Coding blog in a bite size

replace multiple words in a string in Ruby

Code snippet on how to replace multiple words in a string in Ruby

string = "Hello, my name is John and I'm from Spain"

replace_words = {"John" => "Mary", "Spain" => "Australia"}

replace_words.each do |old_word, new_word|
  string.gsub!(old_word, new_word)
end

puts string
# Hello, my name is Mary and I'm from Australia

This code replaces multiple words in a string using Ruby. First, the initial string is saved as the variable ‘string’. Next, a hash variable called ‘replace_words’ is created. This variable stores the words to replace, the keys being the original words, and the values being the words to replace with. Then, the ‘each’ loop is used to go through all elements in the ‘replace_words’ hash, and the ‘gsub!’ method is used to replace the words in the ‘string’ variable. Finally, the updated string is printed.

ruby