I'm new to Ruby and am trying to work something out which is confusing me. While writing a simple parser, I found that comparing a char with a ==
would produce a different result than comparing it with a case
expression:
File.open('Quote.txt') do |f|
f.chars.each do |c|
puts c == '"' ? 'Quote' : 'Err'
puts case c
when '"' then 'QuoteCase'
else 'ErrCase'
end
p c == '"', c === '"', c
end
end
Assuming Quote.txt
is a 1-byte file containing a single quote character (0x22
), this produces:
Quote
ErrCase
true
true
"\""
I'm assuming I've done something wrong, but I can't figure out what it is. Can anyone help?
This is in Ruby 1.9.2, by the way.
case
uses the triple-equal ===
operator to check each case.
That said, I don't know why your example isn't working:
> c = "\""
> c == "\""
=> true
> c === "\""
=> true
Try removing the .each
and explicitly setting c
to the quote character and see what happens.
Generally, ===
is more forgiving than ==
in Ruby, so I can't imagine a case where ==
would match and ===
wouldn't.
Edit: I've just copied your code, with the same input (a file with a single "
character) and got the following output:
Quote
QuoteCase
Err
ErrCase
(the last two are from the newline at the end of the file that Vim insists on).
It looks like a bug in YARV on windows. I get the correct output in JRuby 1.6.0:
# ruby -v
ruby 1.9.2p180 (2011-02-18) [i386-mingw32]
# ruby test.rb
Quote
ErrCase
true
true
"\""
# jruby --1.9 -v
jruby 1.6.0 (ruby 1.9.2 patchlevel 136) (2011-03-15 f3b6154) (Java HotSpot(TM) Client VM 1.7.0-ea) [Windows XP-x86-java]
# jruby --1.9 test.rb
Quote
QuoteCase
true
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