Skip to content
instance method

String#tr

(::String::selector source, ::string relpacement) -> ::String
tr(selector, replacements) → new_string

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 selector is translated to the first character in replacements.

  • Each occurrence of the second character specified by selector is translated to the second character in replacements.

  • And so on.

Example:

Example
'hello'.tr('el', 'ip') #=> "hippo"

If replacements is shorter than selector, it is implicitly padded with its own last character:

Example
'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:

Example
'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

  1. 3.0
See also #tr! #to_sym #to_str #tr_s also in 4.1 · 3.4 · 3.3 · 3.2 · 3.1 · 3.0