Ruby craziness: Class vs Object?

后端 未结 7 1820
陌清茗
陌清茗 2020-12-07 08:53

I just started playing with JRuby. This is my first ruby post. I had a hard time understanding classes vs objects in Ruby. It doesnt mean like what classes & objects in

7条回答
  •  庸人自扰
    2020-12-07 09:14

    In Ruby, everything is an Object including classes and modules. Object is the most low-level class (well, in Ruby 1.9.2 there is also BasicObject but this is an other story).

    See the following output.

    > Object.ancestors
    # => [Object, Kernel, BasicObject] 
    > Class.ancestors
    # => [Class, Module, Object, Kernel, BasicObject] 
    > Module.ancestors
    # => [Module, Object, Kernel, BasicObject] 
    > String.ancestors
    # => [String, Comparable, Object, Kernel, BasicObject]
    

    As you can see, both Class and Module inherits from Object.

    Back to your original assertions, you have to understand the difference bewteen

    • is_a?
    • kind_of'
    • instance_of?

    They are not interchangeable. is_a? and kind_of? returns true if other is the same class or an ancestor. Conversely, instance_of? returns true only if other is the same class.

    > Class.is_a? Object
    # => true 
    > Class.kind_of? Object
    # => true 
    > Class.instance_of? Object
    # => false 
    

提交回复
热议问题