tags:

views:

81

answers:

3

I came across the following code and couldn't figure out what was going on.

def self.eof_packet?(data)
  data[0] == ?\xfe && data.length == 5
end
+2  A: 

Hexadecimal number FE, which is 254

Nikita Rybak
Not accurate. While in Ruby 1.8 `?\xfe == 254`, this is not the case in Ruby 1.9, since `?\xfe` is actually `String`, not a number.
Marc-André Lafortune
@Marc, useful comment. However, it doesn't warrant a down-vote (don't know if that was you). Ruby's penchant for breaking compatibility in minor revisions has tripped up many an experienced programmer. @Nikita's answer is completely correct for 1.8, where `?\xfe` is a Fixnum.
Matthew Flaschen
Thanks very much, all of you.
aharon
@Matthew: The given code compares `data[0]` (a character) with `?\xfe` (a character). That code is fine and it will work in both Ruby 1.8 and 1.9. I feel SO is a great site to educate and learn. I don't think it's a good idea that anyone confuses `?\xfe` with a number and nobody should write `data[0] == 0xFE`I don't mean to be rude; my understanding is that a downvote is appropriate for an incorrect answer. I'll gladly revert it if this answer gets corrected.BTW, Ruby 1.9 is anything but a minor revision...
Marc-André Lafortune
@Marc, in 1.8, `data[0]`, `254`, `?\xfe`, and `0xFE` are all Fixnums and thus `data[0] == ?\xfe`, `data[0] == 0xFE`, and `data[0] == 254` are all correctly comparing objects of the same type. This is true regardless of whether `data` is a `String` or `Array`. Wikipedia and other sources define the minor revision as the part after the period.
Matthew Flaschen
+1  A: 

It's a hexadecimal character literal. You can also use 0xfe, which also works for larger numbers (e.g. 0x100) that don't fit in a byte.

Matthew Flaschen
+5  A: 

? starts a character literal.

\x starts a hexadecimal escape.

Ken