In many languages there\'s a pair of functions, chr()
and ord()
, which convert between numbers and character values. In some languages, ord()
Try:
'A'.unpack('c')
Just came across this while putting together a pure Ruby version of Stringprep via RFCs.
Beware that chr
fails outside [0,255], instead use 1.9.x - 2.1.x portable replacements:
[22] pry(main)> "\u0221".ord.chr
RangeError: 545 out of char range
from (pry):2:in 'chr'
[23] pry(main)> x = "\u0221".unpack('U')[0]
=> 545
[24] pry(main)> [x].pack('U')
=> "ȡ"
[25] pry(main)>
If String#ord didn't exist in 1.9, it does in 2.0:
"A".ord #=> 65
I'm writing code for 1.8.6 and 1.9.3 and I couldn't get any of these solutions to work in both environments :(
However, I came across another solution: http://smajnr.net/2009/12/ruby-1-8-nomethoderror-undefined-method-ord-for-string.html
That didn't work for me either but I adapted it for my use:
unless "".respond_to?(:ord)
class Fixnum
def ord
return self
end
end
end
Having done that, then the following will work in both environments
'A'[0].ord