Difference between == and case?

I'm new to Ruby and trying to do something that scares me. When writing a simple parser, I found that comparing char with == 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 pc == '"', c === '"', c end end 

Assuming Quote.txt is a 1-byte file containing a single quote ( 0x22 ), this gives:

 Quote ErrCase true true "\"" 

I assume that I did something wrong, but I can’t understand what it is. Can anyone help?

This, by the way, is in Ruby 1.9.2.

+6
ruby file parsing
source share
2 answers

Looks like a YARV error 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 "\"" 
+2
source share

case uses the triple-equal === operator to test each case.

However, I do not know why your example does not work:

 > c = "\"" > c == "\"" => true > c === "\"" => true 

Try removing .each and explicitly setting c to the quote character and see what happens.

As a rule, === more forgiving than == in Ruby, so I can’t imagine the case when == will match, but === will not.

Edit: I just copied your code with the same input (file with a single character " ) and received the following output:

 Quote QuoteCase Err ErrCase 

(last two from a new line at the end of the file that Vim insists on).

+3
source share

All Articles