Method: String#gsub
- Defined in:
- string.c
#gsub(pattern, replacement) ⇒ String #gsub(pattern, hash) ⇒ String #gsub(pattern) {|match| ... } ⇒ String #gsub(pattern) ⇒ Object
Returns a copy of str with all occurrences of pattern substituted for the second argument. The pattern is typically a Regexp; if given as a String, any regular expression metacharacters it contains will be interpreted literally, e.g. \d
will match a backslash followed by ‘d’, instead of a digit.
If replacement
is a String it will be substituted for the matched text. It may contain back-references to the pattern’s capture groups of the form \d
, where d is a group number, or \k<n>
, where n is a group name. Similarly, \&
, \'
, \`
, and +
correspond to special variables, $&
, $'
, $`
, and $+
, respectively. (See regexp.rdoc for details.) \0
is the same as \&
. \\
is interpreted as an escape, i.e., a single backslash. Note that, within replacement
the special match variables, such as $&
, will not refer to the current match.
If the second argument is a Hash, and the matched text is one of its keys, the corresponding value is the replacement string.
In the block form, the current match string is passed in as a parameter, and variables such as $1
, $2
, $`
, $&
, and $'
will be set appropriately. (See regexp.rdoc for details.) The value returned by the block will be substituted for the match on each call.
When neither a block nor a second argument is supplied, an Enumerator is returned.
"hello".gsub(/[aeiou]/, '*') #=> "h*ll*"
"hello".gsub(/([aeiou])/, '<\1>') #=> "h<e>ll<o>"
"hello".gsub(/./) {|s| s.ord.to_s + ' '} #=> "104 101 108 108 111 "
"hello".gsub(/(?<foo>[aeiou])/, '{\k<foo>}') #=> "h{e}ll{o}"
'hello'.gsub(/[eo]/, 'e' => 3, 'o' => '*') #=> "h3ll*"
Note that a string literal consumes backslashes. (See syntax/literals.rdoc for details on string literals.) Back-references are typically preceded by an additional backslash. For example, if you want to write a back-reference \&
in replacement
with a double-quoted string literal, you need to write: "..\\&.."
. If you want to write a non-back-reference string \&
in replacement
, you need first to escape the backslash to prevent this method from interpreting it as a back-reference, and then you need to escape the backslashes again to prevent a string literal from consuming them: "..\\\\&.."
. You may want to use the block form to avoid a lot of backslashes.
5571 5572 5573 5574 5575 |
# File 'string.c', line 5571
static VALUE
rb_str_gsub(int argc, VALUE *argv, VALUE str)
{
return str_gsub(argc, argv, str, 0);
}
|