Ruby Program to convert a string to ASCII code

Computers can only understand ones and zeros. To represent strings of characters in computers, we need a way to convert them to numeric form. This conversion process is called encoding.

There are several character encoding schemes that support different character sets. One of the earliest character encoding standard is ASCII (American Standard Code for Information Exchange).

ASCII can encode up to 127 characters that includes Alphabets (A-za-z), digits (0-9), special characters ([{}]%@), and control characters (\r, \n). You can find the complete ASCII table here.

In this article, you’ll learn how to convert (encode) a character to ASCII code and vice versa in Ruby.

Convert a String or Character to ASCII code in Ruby

You can convert a character to its ASCII value in Ruby using the ord() function:

"a".ord
# 97

Here is how you can convert multiple characters to their ASCII value:

"abc".bytes
# [97, 98, 99]

Convert an ASCII value to its corresponding character in Ruby

If you have an integer ranging from 0 to 127, you can get its associated character in the ASCII character set using use the chr() function:

97.chr
# a

You can convert multiple integers to a string in the ASCII character set like so:

[97,98,99,100].pack('c*')
=> "abcd"