views:

1244

answers:

4

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 String#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.

+1  A: 

How about

puts ?A

GregD
+3  A: 

Try:

'A'.unpack('c')
dylanfm
Now that Ruby 1.9 has changed the meaning of 'A'[0], this is the more portable method.
AShelly
A: 

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
Kent Fredric
+5  A: 

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.

Robert Gamble
It's unfortunate that the "correct" way in Ruby 1.9 is so long, but at least it'll show up easier in searches for "ord".Thanks for your very detailed answer.
RJHunter
'A'[0].ord words in ruby 1.8.7 - and thanks for the answer.
Kyle Burton