Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

ruby double question mark [duplicate]

Tags:

ruby

I came across this piece of ruby code:

str[-1]==??

What is the double question mark all about? Never seen that before.

like image 429
Cameron Avatar asked Feb 06 '10 14:02

Cameron


2 Answers

Ruby 1.8 has a ?-prefix syntax that turns a character into its ASCII code value. For example, ?a is the ASCII value for the letter a (or 97). The double question mark you see is really just the number 63 (or the ASCII value for ?).

?a    # => 97
?b    # => 98
?c    # => 99
?\n   # => 10
??    # => 63

To convert back, you can use the chr method:

97.chr   # => "a"
10.chr   # => "\n"
63.chr   # => "?"

??.chr   # => "?"

In Ruby 1.9, the ?a syntax returns the character itself (as does the square bracket syntax on strings):

??           # => "?"

"What?"[-1]  # => "?"
like image 189
Ryan McGeary Avatar answered Oct 14 '22 10:10

Ryan McGeary


As Ryan says, the ? prefix gives you the ASCII value of a character. The reason why this is useful in this context is that when you use the index notation on a string in Ruby 1.8 the ASCII value is returned rather than the character. e.g.

irb(main):009:0> str = 'hello'
=> "hello"
irb(main):010:0> str[-1]
=> 111

so the following wouldn't test if the last character of a string was the letter 'o'

irb(main):011:0> str[-1] == 'o'
=> false

but this would:

irb(main):012:0> str[-1] == ?o
=> true

and (provided you know what the ? does!) this is slightly clearer than

irb(main):013:0> str[-1] == 111
=> true
like image 28
mikej Avatar answered Oct 14 '22 10:10

mikej