开发者

Class and case statements -- why doesn't this evaluate as expected?

k = Integer
case k
  when Integer
    "HI"
  else "BYE"
end

In ruby 1.8, this evaluates to "BYE". I would anticipate it to evaluate to "H开发者_如何学PythonI" as Integer == Integer evaluates to true. What operator does the when statement use? Is there something I'm missing??


case expressions use the === operator of the object in the when clause. So it evaluates to Integer === k. The tricky thing here is that Class#=== is essentially implemented this way:

class Class
  def ===(obj)
    obj.kind_of? self
  end
end

This is meant for methods that can accept many classes in the same parameter, so it's easy to test the argument's type and treat it appropriately. But as you can see, it's not an identity test. So it's testing whether Integer is an instance of Integer — which it isn't (it's an instance of Class).

Depending on your exact use case, a Hash might be closer to what you want.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜