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.
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:
That line of code prints the number
97, the decimal value of the character
A little more
Here's a little more information, in the form of some slightly-commented output from a Ruby
>> ?A => 65 >> ?a => 97 >> ?~ => 126 # a space >> ?\s => 32 # tab >> ?\t => 9 # newline >> ?\n => 10 # carriage-return >> ?\r => 13
There’s just one person behind this website; if this article was helpful (or interesting), I’d appreciate it if you’d share it. Thanks, Al.