String#tr
static VALUE
rb_str_tr(VALUE str, VALUE src, VALUE repl)
{
str = str_duplicate(rb_cString, str);
tr_trans(str, src, repl, 0);
return str;
}
Returns a copy of self with each character specified by string selector translated to the corresponding character in string replacements. The correspondence is positional:
-
Each occurrence of the first character specified by
selectoris translated to the first character inreplacements. -
Each occurrence of the second character specified by
selectoris translated to the second character inreplacements. -
And so on.
Example:
'hello'.tr('el', 'ip') #=> "hippo"
If replacements is shorter than selector, it is implicitly padded with its own last character:
'hello'.tr('aeiou', '-') # => "h-ll-" 'hello'.tr('aeiou', 'AA-') # => "hAll-"
Arguments selector and replacements must be valid character selectors (see Character Selectors), and may use any of its valid forms, including negation, ranges, and escapes:
'hello'.tr('^aeiou', '-') # => "-e--o" # Negation. 'ibm'.tr('b-z', 'a-z') # => "hal" # Range. 'hel^lo'.tr('\^aeiou', '-') # => "h-l-l-" # Escaped leading caret. 'i-b-m'.tr('b\-z', 'a-z') # => "ibabm" # Escaped embedded hyphen. 'foo\\bar'.tr('ab\\', 'XYZ') # => "fooZYXr" # Escaped backslash.
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]
-