Ruby - How to convert characters to ASCII decimal (byte) values

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:

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


Share it!

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.

Add new comment

The content of this field is kept private and will not be shown publicly.

Anonymous format

  • Allowed HTML tags: <em> <strong> <cite> <code> <ul type> <ol start type> <li> <pre>
  • Lines and paragraphs break automatically.
By submitting this form, you accept the Mollom privacy policy.