Skip to content

Preview Ruby 4.1 is a preview. It can change before the final release. Switch to Ruby 4.0 →

instance method

String#tr

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

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:

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 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. 4.1
  2. 3.0
See also #tr! #to_sym #to_str #tr_s also in 4.0 · 3.4 · 3.3 · 3.2 · 3.1 · 3.0