Search code examples
rubyasciicharacter

ASCII value of character in Ruby


How do I obtain the ASCII value of a character in Ruby 1.9?

I searched the Internet far and wide, but without success. I tried ?x and "x"[0], but all they return is "x".


Solution

  • The String#ord method will do the trick:

    ruby-1.9.2-p136 > 'x'.ord
     => 120 
    ruby-1.9.2-p136 > '0'.ord
     => 48 
    ruby-1.9.2-p136 > ' '.ord
     => 32