Ruby class types and case statements

后端 未结 5 1548
野趣味
野趣味 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条回答
  •  旧时难觅i
    2020-12-02 08:18

    Yeah, Nakilon is correct, you must know how the threequal === operator works on the object given in the when clause. In Ruby

    case item
    when MyClass
    ...
    when Array
    ...
    when String
    ...
    

    is really

    if MyClass === item
    ...
    elsif Array === item
    ...
    elsif String === item
    ...
    

    Understand that case is calling a threequal method (MyClass.===(item) for example), and that method can be defined to do whatever you want, and then you can use the case statement with precisionw

提交回复
热议问题