Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Integer value of a character in ruby?

Tags:

ruby

I am looking to turn the character 'a' into 97 in ruby 1.9.2

Ruby 1.8.7

irb(main):001:0> ?a => 97 

Ruby 1.9.2

irb(main):001:0> ?a => "a" 
like image 485
Jeremy Avatar asked Nov 06 '10 00:11

Jeremy


People also ask

How do you get an integer in Ruby?

To convert an string to a integer, we can use the built-in to_i method in Ruby. The to_i method takes the string as a argument and converts it to number, if a given string is not valid number then it returns 0.

What are the two integer classes of Ruby?

In Ruby, Integer class is the basis for the two concrete classes that hold whole numbers. These concrete classes are Bignum and Fixnum. Fixnum holds integer values that are shown in the native machine word, whereas Bignum holds the integer value outside the range of Fixnum.

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 .


Video Answer


2 Answers

You probably want String#ord:

% irb ruby-1.9.2-head > 'a'.ord  => 97  
like image 129
Chris Johnsen Avatar answered Sep 22 '22 16:09

Chris Johnsen


For those, who are looking for the opposite of ord. We have chr

>> "A".ord => 65 >> 65.chr => "A" 
like image 32
lokeshjain2008 Avatar answered Sep 21 '22 16:09

lokeshjain2008