Ruby class types and case statements

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

    In Ruby, a class name is a constant that refers to an object of type Class that describes a particular class. That means that saying MyClass in Ruby is equivalent to saying MyClass.class in Java.

    obj.class is an object of type Class describing the class of obj. If obj.class is MyClass, then obj was created using MyClass.new (roughly speaking). MyClass is an object of type Class that describes any object created using MyClass.new.

    MyClass.class is the class of the MyClass object (it's the class of the object of type Class that describes any object created using MyClass.new). In other words, MyClass.class == Class.

提交回复
热议问题