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

RJHunter picture RJHunter · Nov 21, 2008 · Viewed 79.1k times · Source

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.

Answer

Rob Cameron picture Rob Cameron · Dec 10, 2013

If String#ord didn't exist in 1.9, it does in 2.0:

"A".ord #=> 65