Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

ASCII value of character in Ruby

How do I obtain the ASCII value of a character in Ruby 1.9?

I searched the Internet far and wide, but without success. I tried ?x and "x"[0], but all they return is "x".

like image 222
LakatosI Avatar asked Mar 03 '11 11:03

LakatosI


People also ask

Is Ascii a character?

ASCII is a 7-bit character set containing 128 characters. It contains the numbers from 0-9, the upper and lower case English letters from A to Z, and some special characters. The character sets used in modern computers, in HTML, and on the Internet, are all based on ASCII.

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.


2 Answers

The String#ord method will do the trick:

ruby-1.9.2-p136 > 'x'.ord  => 120  ruby-1.9.2-p136 > '0'.ord  => 48  ruby-1.9.2-p136 > ' '.ord  => 32  
like image 51
Mark Rushakoff Avatar answered Sep 22 '22 22:09

Mark Rushakoff


You can also use

ruby-2.0.0p353 > "x".sum => 120  ruby-2.0.0p353 > "a string".sum => 792  

The 'sum' method will find the sum of all character codes, but if you put only one character it will give you the code of that one only.

like image 42
Sh.K Avatar answered Sep 21 '22 22:09

Sh.K