How to Use the Ruby ord Method

09/24/2021

Contents

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

Using the ord method

The ord method in Ruby is a built-in method that returns the integer ordinal of a one-character string. In other words, it returns the ASCII value of the character.

Here’s how to use the ord method in Ruby:

Call the ord method on a one-character string.
For example:

char = "a"
char.ord # => 97

In this example, the ord method is called on the string “a”, and it returns the integer 97, which is the ASCII value for the letter “a”.

Store the result of the ord method in a variable.
For example:

char = "b"
ascii_value = char.ord
puts ascii_value # => 98

In this example, the ord method is called on the string “b”, and its result is stored in the variable ascii_value. The puts method is then used to print the value of ascii_value, which is 98.

Use the ord method in conjunction with other methods that accept ASCII values as input.
For example:

ascii_value = "A".ord
puts ascii_value.chr.downcase # => "a"

In this example, the ord method is called on the string “A”, and its result is stored in the variable ascii_value. The chr method is then called on ascii_value to convert the integer back to a character. Finally, the downcase method is called on the resulting string to convert it to lowercase.

Note that the ord method only works on one-character strings. If you try to call it on a string with more than one character, you’ll get an error:

str = "hello"
str.ord # => NoMethodError: undefined method `ord' for "hello":String