Ruby class types and case statements

后端 未结 5 1545
野趣味
野趣味 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:32

    It depends on the nature of your item variable. If it is an instance of an object, e.g.

    t = 5
    

    then

    t.class == Fixnum
    

    but if it is a class in itself e.g

    t = Array
    

    then it will be a Class object, so

    t.class == Class
    

    EDIT: please refer to How to catch Errno::ECONNRESET class in "case when"? as stated by Nakilon since my answer could be wrong.

提交回复
热议问题