sscirrus
sscirrus

Reputation: 56719

Convert variables to ASCII in Rails

In Rails (Ruby 1.9+), you can call ?a.ord to get the ascii character for "a".

How can you do the same thing for a variable that contains a single character?

myvar = "a"
?myvar.ord      # fails
?(myvar).ord    # fails
?[myvar].ord    # fails
?{myvar}.ord    # fails

Upvotes: 1

Views: 932

Answers (3)

mu is too short
mu is too short

Reputation: 434635

?a.ord is equivalent to this:

s = ?a
s.ord

So all you need to do is call the String#ord method on your string:

myvar.ord

Keep in mind that ?a is the same as 'a', it is just a (rather strange) shorthand for creating single character strings.

Upvotes: 2

tyamagu2
tyamagu2

Reputation: 969

myvar = "a"
myvar.ord # => 97

String#ord is a method that returns the codepoint of the first character of the receiver string, so you can just call it on a variable that contains a string object.

?a is a way of writing a string that represents the character a.

Upvotes: 1

osman
osman

Reputation: 2469

"a".ord You can check out the ruby docs API to verify http://ruby-doc.org/core-1.9.3/String.html

Upvotes: 0

Related Questions