To replace all occurrences of a substring in a string in Ruby, you can use the gsub
method.
In this example,
str
.gsub
method on str
with the substring to be replaced and the replacement string as arguments.gsub
method returns a new string with all occurrences of the substring replaced.str = 'Hello World Hello'
new_str = str.gsub('Hello', 'Hi')
puts new_str
Hi World Hi
In this example,
str
.gsub
method on str
with a regular expression to match the character 'o', and the replacement string as arguments.gsub
method returns a new string with all occurrences of the character replaced.str = 'Hello World Hello'
new_str = str.gsub('o', 'X')
puts new_str
HellX WXrld HellX
In this tutorial, we learned How to Replace All Occurrences of a Substring in a String in Ruby language with well detailed examples.