String#tr

str.tr(from_str, to_str) -> string
Returns: string · Added in v1.0 · Updated March 13, 2026 · String Methods
string translation character-replacement

String#tr performs character‑by‑character translation: each character in the receiver that appears in from_str is replaced by the corresponding character in to_str. If to_str is shorter than from_str, its last character is repeated as needed. The translation is performed left‑to‑right, and the result is always a new string—the original is never modified.

Syntax

str.tr(from_str, to_str) -> new_string

Parameters

ParameterTypeDefaultDescription
from_strString(required)A set of characters to be replaced.
to_strString(required)A set of replacement characters. Each character in from_str is mapped to the character at the same position in to_str. If to_str is shorter, its last character is used for all extra characters in from_str.

Examples

Basic character replacement

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

Explanation: ei, lp.

Shorter to_str

"abcde".tr("bcd", "xy")
# => "axyxe"

Mapping: bx, cy, dy (last character of to_str repeats).

Range notation

"12345".tr("1-5", "a-e")
# => "abcde"

Ranges 1-5 and a-e expand to 12345 and abcde respectively.

Delete characters with empty to_str

"hello world".tr("aeiou", "")
# => "hll wrld"

Vowels are deleted because to_str is empty.

Case‑insensitive translation

"Hello".tr("A-Z", "a-z")
# => "hello"

Uppercase letters are replaced by their lowercase equivalents.

Common Patterns

Simple cipher (Caesar shift)

def caesar(str, shift)
  alphabet = "abcdefghijklmnopqrstuvwxyz"
  shifted = alphabet.chars.rotate(shift).join
  str.tr(alphabet, shifted)
end

caesar("hello", 3)
# => "khoor"

Sanitising filenames

def sanitise_filename(name)
  name.tr("/\\:*?\"<>|", "_")
end

sanitise_filename("my/file:name.txt")
# => "my_file_name.txt"

Converting spaces to underscores

"user profile".tr(" ", "_")
# => "user_profile"

Removing punctuation

"Hello, world!".tr(",.!?", "")
# => "Hello world"

Errors

  • ArgumentError: raised if from_str or to_str are not strings.
  • Encoding::CompatibilityError: raised if the encodings of the strings are incompatible.

Note: tr does not support regex patterns—use gsub for that.

See Also