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
.
chr is a String class method in Ruby which is used to return a one-character string at the beginning of the string. Parameters: Here, str is the given string. Returns: A one-character string at the beginning of the string.
The ord method is used to return the integer ordinal of a one-character string.
In double quoted strings, you can write escape sequences and Ruby will output their translated meaning. A \n becomes a newline. In single quoted strings however, escape sequences are escaped and return their literal definition. A \n remains a \n .
You can read more in Ruby's docs for regular expressions. lookAhead =~ /[[:alnum:]]/ if you just want to check whether the char is alphanumeric without needing to know which.
If String#ord didn't exist in 1.9, it does in 2.0:
"A".ord #=> 65
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With