What's the opposite of chr() in Ruby?

Viewed 84033

In many languages there's a pair of functions, chr() and ord(), which convert between numbers and character values. In some languages, ord() is called asc().

Ruby has Integer#chr, which works great:

>> 65.chr
A

Fair enough. But how do you go the other way?

"A".each_byte do |byte|
   puts byte
end

prints:

65

and that's pretty close to what I want. But I'd really rather avoid a loop -- I'm looking for something short enough to be readable when declaring a const.

10 Answers

In Ruby up to and including the 1.8 series, the following will both produce 65 (for ASCII):

puts ?A
'A'[0]

The behavior has changed in Ruby 1.9, both of the above will produce "A" instead. The correct way to do this in Ruby 1.9 is:

'A'[0].ord

Unfortunately, the ord method doesn't exist in Ruby 1.8.

Additionally, if you have the char in a string and you want to decode it without a loop:

puts 'Az'[0]
=> 65
puts 'Az'[1]
=> 122
Related