Understanding ruby .class and .ancestors methods

后端 未结 1 1040
难免孤独
难免孤独 2020-12-07 14:56

I have a class defined as below

class Order
end

puts Order.class #-> Class
puts Order.ancestors #-> [Order, Object, Kernel, BasicObject]

puts Order.c         


        
相关标签:
1条回答
  • 2020-12-07 15:26

    For that you need to see how the Ruby object model looks.

    Ruby object model diagram

    That means the classes created using keyword class will always be the subclass of Object by default. Class is not the superclass of your class Order, rather it is an instance of class Class.Module#ancestors will include list of modules included in mod (including mod itself) and the superclass of your class Order.

    class Order;end
    Order.superclass # => Object
    Order.superclass.superclass # => BasicObject
    Order.superclass.included_modules # => [Kernel]
    

    So if you look at the output and understand the above code,then the below should now be clear to you:

    Order.ancestors #-> [Order, Object, Kernel, BasicObject]
    

    Now see,

    class Order;end
    Order.class # => Class
    Order.instance_of? Class # => true
    Order.class.superclass # => Module
    Order.class.superclass.superclass # => Object
    Order.class.superclass.superclass.included_modules # => [Kernel]
    

    So if you look at the output and understand the above code, then the below should now be clear to you:

    Order.class.ancestors #->[Class, Module, Object, Kernel, BasicObject]
    

    That said Order.ancestors is giving you the ancestors of the class Order,whereas Order.class.ancestors is giving you the ancestors of the Class.

    0 讨论(0)
提交回复
热议问题