Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

ruby

ascii

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.

like image 643
RJHunter Avatar asked Nov 21 '08 13:11

RJHunter


People also ask

What is CHR in Ruby?

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.

What is Ord method in Ruby?

The ord method is used to return the integer ordinal of a one-character string.

What does \n do in Ruby?

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 .

How do you check if a character is a letter in Ruby?

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.


1 Answers

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

"A".ord #=> 65 
like image 52
Rob Cameron Avatar answered Sep 27 '22 18:09

Rob Cameron