To replace all occurrences of a substring in a string using regular expression in Ruby, you can use the gsub
method.
In this example,
str
.gsub
method to replace all occurrences of "Hello" with "Hi".str = 'Hello World Hello'
new_str = str.gsub(/Hello/, 'Hi')
puts new_str
Hi World Hi
In this example,
str
.gsub
method to replace all occurrences of digits (\d) with 'Y'.str = 'Hello123World789'
new_str = str.gsub(/\d/, 'Y')
puts new_str
HelloYYYWorldYYY
In this tutorial, we learned How to Replace a Substring in a String using Regular Expression in Ruby language with well detailed examples.