How to Use the Ruby chr Method

09/25/2021

Contents

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

Using the chr Method

The chr method is a built-in method in Ruby that converts an integer to its corresponding ASCII character. It takes an integer as an argument and returns the ASCII character that corresponds to that integer.

Here’s how you can use the chr method in Ruby:

Basic usage

# Convert an integer to its corresponding ASCII character
97.chr # Output: "a"

In this example, the integer 97 represents the ASCII value for the lowercase letter “a”. The chr method returns the corresponding character, which is “a”.

Using chr with a loop

# Print all ASCII characters using a loop
for i in 0..127 do
  print i.chr
end

This code prints all ASCII characters from 0 to 127, using a loop and the chr method. The for loop iterates through each integer value in the range of 0 to 127, and the chr method is used to convert each integer to its corresponding ASCII character.

Using chr with Unicode

# Convert Unicode code point to character
128169.chr(Encoding::UTF_8) # Output: "🚀"

In this example, the integer 128169 represents a Unicode code point. The chr method is used with the Encoding::UTF_8 argument to convert the integer to its corresponding Unicode character. The output is the rocket emoji “🚀”.

Using chr with a string

# Convert each character code to its corresponding character
"104 101 108 108 111".split(" ").map(&:to_i).map(&:chr).join # Output: "hello"

In this example, a string of space-separated integers is converted to its corresponding characters using the chr method. The string is first split into an array of integers using the split method, and then each integer is converted to its corresponding character using the map method and the chr method. Finally, the resulting array of characters is joined back into a string, which is the output.