x ==用户返回true,但case x语句不运行与User关联的块.这里发生了什么事?
u = User.new # => #<User:0x00000100a1e948> x = u.class # => User x == User # => true case x when User puts "constant" when "User" puts "string" else puts "nothing?" end # => nothing?
解决方法
案例比较使用===而不是==.对于许多对象,===和==的行为是相同的,请参阅数字和字符串:
5 == 5 #=> true 5 === 5 #=> true "hello" == "hello" #=> true "hello" === "hello" #=> true
但对于其他类型的对象===可能意味着许多事情,完全取决于接收者.
对于类的情况,===测试对象是否是该类的实例:
Class === Class.new #=> true.
对于Range,它会检查对象是否属于该范围:
(5..10) === 6 #=> true
对于Procs,===实际调用Proc:
multiple_of_10 = proc { |n| (n % 10) == 0 } multiple_of_10 === 20 #=> true (equivalent to multiple_of_10.call(20))
对于其他对象,请检查其对===的定义以揭示其行为.它并不总是很明显,但它们通常会产生某种意义.
以下是将所有内容放在一起的示例:
case number when 1 puts "One" when 2..9 puts "Between two and nine" when multiple_of_10 puts "A multiple of ten" when String puts "Not a number" end
有关详细信息,请参阅此链接:http://www.aimred.com/news/developers/2008/08/14/unlocking_the_power_of_case_equality_proc/