ASCII value of character in Ruby
32,468
Solution 1
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
Solution 2
You can also use
ruby-2.0.0p353 > "x".sum
=> 120
ruby-2.0.0p353 > "a string".sum
=> 792
The 'sum' method will find the sum of all character codes, but if you put only one character it will give you the code of that one only.
Solution 3
x.ord
http://www.ruby-doc.org/core/classes/String.html#M001177
Author by
LakatosI
Updated on December 16, 2020Comments
-
LakatosI over 3 years
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".
-
Jonas Elfström about 9 yearsIt also seems that .ord needs correct UTF-8 but that .sum does not care.
-
jasonleonhard over 8 years0.ord will work, returning 0, the ascii value. However, 0.sum will not, it returns undefined method for Fixnum.
-
Cristik almost 3 yearsThis doesn't give correct results for Unicode characters:
"€".ord => 8364
, while"€".sum => 528