String#gsub
static VALUE
rb_str_gsub(int argc, VALUE *argv, VALUE str)
{
return str_gsub(argc, argv, str, 0);
}
Returns a copy of self with zero or more substrings replaced.
Argument pattern may be a string or a Regexp; argument replacement may be a string or a Hash. Varying types for the argument values makes this method very versatile.
Below are some simple examples; for many more examples, see Substitution Methods.
With arguments pattern and string replacement given, replaces each matching substring with the given replacement string:
s = 'abracadabra' s.gsub('ab', 'AB') # => "ABracadABra" s.gsub(/[a-c]/, 'X') # => "XXrXXXdXXrX"
With arguments pattern and hash replacement given, replaces each matching substring with a value from the given replacement hash, or removes it:
h = {'a' => 'A', 'b' => 'B', 'c' => 'C'} s.gsub(/[a-c]/, h) # => "ABrACAdABrA" # 'a', 'b', 'c' replaced. s.gsub(/[a-d]/, h) # => "ABrACAABrA" # 'd' removed.
With argument pattern and a block given, calls the block with each matching substring; replaces that substring with the block’s return value:
s.gsub(/[a-d]/) {|substring| substring.upcase } # => "ABrACADABrA"
With argument pattern and no block given, returns a new Enumerator.
Related: see Converting to New String.
Ruby version changes
-
3.0
-
The following methods now return or yield
Stringinstances instead of subclass instances when called on subclass instances: [Bug #10845]
-