OneBite.Dev - Coding blog in a bite size

replace a substring within a string in Ruby

Code snippet on how to replace a substring within a string in Ruby

 str = "Hello world!"
 new_str = str.gsub("world", "everyone")
 puts new_str

This code enables a user to replace a substring within a string. The code first defines a string ‘str’ as “Hello World!“. Then, it assigns a new string ‘new_str’, which replaces the substring “world” with “everyone” using the ‘.gsub’ method. Finally, it prints the output to the terminal using ‘puts new_str’.

ruby