In weekly code review, GL mentioned a weird issues :

1
2
3
4
5
6
7
8
9
10
def self.test(obj)
    case obj.class
    when Student, TrialPlan
      puts "1"
    when Call
      puts "2"
    else
      puts "3"
    end
end

This doesn’t behave as expected. When we run test(Student.first), it prints out “3″!

but this works fine.

1
2
3
4
5
6
7
8
9
10
def self.test(obj)
    case obj.class.to_s
    when "Student", "TrialPlan"
      puts "1"
    when "Call"
      puts "2"
    else
      puts "3"
    end
end

Then I searched around for explaining this, I found the case statement in Ruby is very different with what in other languages. Ruby implements the Case statement according to its special operator “===”, which is not the same as “==”.

what’s difference? See below explainations:
how-a-ruby-case-statement-works-and-what-you-can-do-with-it/
ruby-case-statement-comparison-feature.html

Leave a Reply

(required)

(required)


*

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>

© 2011 Refactoring Thoughts Suffusion theme by Sayontan Sinha
普人特福的博客cnzz&51la for wordpress,cnzz for wordpress,51la for wordpress