replace a substring in a string in ruby

To replace a particular substring in a string with another substring in Ruby, you can use the gsub method with suitable parameters. gsub stands for global substitution, meaning it will replace all occurrences of the substring.

Here's an example:

main.rb
string = "the quick brown fox jumps over the lazy dog"
new_string = string.gsub("lazy", "busy")
puts new_string # Output: "the quick brown fox jumps over the busy dog"
168 chars
4 lines

In the above example, gsub method takes two arguments, the first being the substring you want to replace ("lazy"), and second being the substring you want to replace it with ("busy"). We then store the new_string in a new variable and output it.

gistlibby LogSnag