Preview Ruby 4.1 is a preview. It can change before the final release. Switch to Ruby 4.0 →
String#tr
static VALUE
rb_str_tr(int argc, VALUE *argv, VALUE str)
{
rb_check_arity(argc, 1, 2);
str = str_duplicate(rb_cString, str);
if (argc == 1) {
VALUE pairs = argv[0];
VALUE result = tr_trans_pairs(str, pairs);
if (NIL_P(result)) result = str;
return str;
}
VALUE src = argv[0], repl = argv[1];
tr_trans(str, src, repl, 0);
return str;
}
Accepts either a selector and a replacements string, or a single pairs Hash.
When a pairs Hash is provided the keys, returns a copy of self with the keys of the hash replaced by the values.
-
They keys must be strings containing a single codepoints.
-
The values can be of any length.
Example:
'hello'.tr('e' => 'er', 'l' => '', 'o' => 'o !') #=> "hero !"
When selector and replacementsare provided, 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
-
4.1
-
String#trnow accept aHashfor multi-character replacement. [Feature #22238]
-
-
3.0
-
The following methods now return or yield
Stringinstances instead of subclass instances when called on subclass instances: [Bug #10845]
-