Ruby class types and case statements

后端 未结 5 1547
野趣味
野趣味 2020-12-02 08:02

What is the difference between

case item.class
when MyClass
  # do something here
when Array
  # do something different here
when String
  # do a third thing         


        
5条回答
  •  醉酒成梦
    2020-12-02 08:31

    You can use:

    case item.class.to_s
        when 'MyClass'
    

    ...when the following twist is not possible:

    case item
        when MyClass
    

    The reason for this is that case uses ===, and the relationship the === operator describes is not commutative. For example, 5 is an Integer, but is Integer a 5? This is how you should think of case/when.

提交回复
热议问题