String#gsub
method in Ruby returns a copy of the String object it is called upon, with all occurences of pattern (first argument) subsituted for the second argument. The pattern is usually a Regexp
.
The replacement can contains back-references (like \1
) to the pattern’s capture groups.
'son'.gsub(/[o]/, 'u') # => "sun"
'rhododendron'.gsub(/([aeiou])/, '<\1>') # => "rh<o>d<o>d<e>ndr<o>n"
A destructive version String#gsub!
, which perform the substitutions in place, is also available.