Dec 092009
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
最新评论