Returns a copy of str with the first occurrence of
pattern replaced with either replacement or the value of
the block. The pattern will typically be a Regexp; if it is a String then no regular expression
metacharacters will be interpreted (that is /\d/ will match a digit, but '\d' will match a backslash followed by a
‘d’).
If the method call specifies replacement, special variables such
as $& will not be useful, as substitution into the string
occurs before the pattern match starts.
However, the sequences \1,\2, etc., may be used.
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. The value returned by the block will be substituted for the
match on each call.
The result inherits any tainting in the original string or any supplied
replacement string.
/*
* call-seq:
* str.sub(pattern, replacement) => new_str
* str.sub(pattern) {|match| block } => new_str
*
* Returns a copy of <i>str</i> with the <em>first</em> occurrence of
* <i>pattern</i> replaced with either <i>replacement</i> or the value of the
* block. The <i>pattern</i> will typically be a <code>Regexp</code>; if it is
* a <code>String</code> then no regular expression metacharacters will be
* interpreted (that is <code>/\d/</code> will match a digit, but
* <code>'\d'</code> will match a backslash followed by a 'd').
*
* If the method call specifies <i>replacement</i>, special variables such as
* <code>$&</code> will not be useful, as substitution into the string occurs
* before the pattern match starts. However, the sequences <code>\1</code>,
* <code>\2</code>, etc., may be used.
*
* In the block form, the current match string is passed in as a parameter, and
* variables such as <code>$1</code>, <code>$2</code>, <code>$`</code>,
* <code>$&</code>, and <code>$'</code> will be set appropriately. The value
* returned by the block will be substituted for the match on each call.
*
* The result inherits any tainting in the original string or any supplied
* replacement string.
*
* "hello".sub(/[aeiou]/, '*') #=> "h*llo"
* "hello".sub(/([aeiou])/, '<\1>') #=> "h<e>llo"
* "hello".sub(/./) {|s| s[0].to_s + ' ' } #=> "104 ello"
*/
static VALUE
rb_str_sub(argc, argv, str)
int argc;
VALUE *argv;
VALUE str;
{
str = rb_str_dup(str);
rb_str_sub_bang(argc, argv, str);
return str;
}
1Note
Cheat Sheet
svoop · Feb 10, 2009
I have written a short introduction and a colorful cheat sheet for Perl Compatible Regular Expressions (PCRE) as used by Ruby’s Regexp class: