Method: String#tr
- Defined in:
- string.c
#tr(selector, replacements) ⇒ Object
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 escaping:
# Negation.
'hello'.tr('^aeiou', '-') # => "-e--o"
# Ranges.
'ibm'.tr('b-z', 'a-z') # => "hal"
# Escapes.
'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.
8654 8655 8656 8657 8658 8659 8660 |
# File 'string.c', line 8654 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; } |