OneBite.Dev - Coding blog in a bite size

replace a word in a string in Ruby

Code snippet on how to replace a word in a string in Ruby

str = "A good programmer is an expert"
str.sub!('good', 'senior')

This code uses the sub! method available in the Ruby String class. Sub! is used primarily to search and replace a particular string. In this case, the code is searching for the word “good” and replacing it with the word “senior”. The result of this code would be “A senior programmer is an expert”. The ! at the end of the sub! method specifies that the actual string object is affected, not just a copy. The str variable is assigned the original string and then the sub! method is used to replace “good” with “senior”.

ruby