tags:

views:

225

answers:

2

I came across this piece of ruby code:

str[-1]==??

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

+17  A: 

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]  # => "?"
Ryan McGeary
Would it be accurate to say that the `?` syntax is deprecated in 1.9, seeing as it serves little purpose now?
Myrddin Emrys
Myrddin, That's probably a fair thing to say. I don't see much point in using `?` syntax in 1.9.
Ryan McGeary
+1  A: 

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
mikej
The above applies for Ruby 1.8, not 1.9 where `"hello"[-1] == "o"`
glenn jackman
This is exactly the reason why, in ruby19, that `?o == "o"`, so that `"hello"[-1] == ?o` in both ruby18 and ruby19.
rampion
Thanks glenn, I've updated the answer to clarify the bit that only applies in 1.8
mikej