How to Use the Ruby tr Method

09/25/2021

Contents

In this article, you will learn how to use the Ruby tr method.

Using the tr method

The tr method in Ruby is used to perform character-level substitutions in a given string. The method takes two arguments: a set of characters to be replaced, and a set of characters to replace them with.

Here’s an example of how to use the tr method:

string = "hello world"
new_string = string.tr('l', 'z')
puts new_string # outputs "hezzo worzd"

In this example, the tr method is called on the string variable, which contains the string “hello world”. The first argument to tr is the character ‘l’, which is the character we want to replace. The second argument is the character ‘z’, which is the character we want to replace ‘l’ with.

So, when tr is called, it replaces all occurrences of ‘l’ in the string with ‘z’, and returns the modified string.

Here’s another example:

string = "hello world"
new_string = string.tr('aeiou', '12345')
puts new_string # outputs "h2ll4 w4rld"

In this example, the first argument to tr is the set of vowels (‘aeiou’), and the second argument is the set of corresponding digits (‘12345’). So, tr replaces all occurrences of vowels in the string with the corresponding digit.

Note that the tr method is case-sensitive. That means if you want to replace both uppercase and lowercase letters, you need to specify both in the argument. For example:

string = "Hello World"
new_string = string.tr('H', 'J')
puts new_string # outputs "Jello World"

To replace both ‘H’ and ‘h’, you would need to call tr with both arguments:

string = "Hello World"
new_string = string.tr('Hh', 'Jj')
puts new_string # outputs "Jello World"

You can also use the tr method to delete characters from a string. To do this, you just need to specify an empty string as the second argument. For example:

string = "hello world"
new_string = string.tr('l', '')
puts new_string # outputs "heo word"

In this example, the second argument to tr is an empty string, which means that all occurrences of ‘l’ in the string are deleted.

The tr method can also be called with the ! modifier, which modifies the original string in place. For example:

string = "hello world"
string.tr!('l', 'z')
puts string # outputs "hezzo worzd"

In this example, the original string is modified in place, so the value of string is changed to the modified string.