All posts

How to replace the contents of a string in Ruby


For this example we will take the string "bacon, eggs" and using that string create a new string, "bacon, orange juice", while leaving the original string intact.

To accomplish this task we will use the String class method gsub. In the most basic use case we will pass two arguments gsub:

  1. The contents of the string we want to replace.
  2. The replacement text.

The result will return a new string with the contents replaced:

bacon_and_eggs = "bacon, eggs"
bacon_and_oj = bacon_and_eggs.gsub("eggs", "orange juice")

=> bacon_and_eggs
"bacon, eggs"
=> bacon_and_oj
"bacon, orange juice"

In more advanced use cases you can pass a pattern you want to match as the first argument to gsub.

Further reading:


I built two products to help fund continued efforts for this website, it would mean a lot if you would check them out:
1. 2500+ Words for the Undermotivated Software Engineer - A short essay I wrote on the titled topic ($3).
2. Build 3 Chrome Extensions in Under 2 Hours - A course I built to teach chrome extension development ($9-20).