I came across this piece of ruby code:
str[-1]==??
What is the double question mark all about? Never seen that before.
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] # => "?"
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With