By Alvin Alexander. Last updated: June 4, 2016
Problem: You have a character, or a string of characters, and you want to use a Ruby script to convert each character to its ASCII decimal (byte) value.
Solution
I just ran into this problem while working on a script to remove binary/garbage characters from a Unix text file. In short, all you have to do to convert a character in Ruby to its equivalent decimal ASCII code is use the ?
operator in front of it, like this:
puts ?a
That line of code prints the number 97
, the decimal value of the character a
.
A little more
Here's a little more information, in the form of some slightly-commented output from a Ruby irb
session:
>> ?A => 65 >> ?a => 97 >> ?~ => 126 # a space >> ?\s => 32 # tab >> ?\t => 9 # newline >> ?\n => 10 # carriage-return >> ?\r => 13