Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why does Object both include Kernel and inherit off it in Ruby?

Tags:

ruby

In Ruby (1.8.X)

Why does Object both inherit off Kernel and include it? Wouldn't just inheriting be enough?

irb(main):006:0> Object.ancestors
=> [Object, Kernel]
irb(main):005:0> Object.included_modules
=> [Kernel]
irb(main):011:0> Object.superclass
=> nil

Note in Ruby 1.9 the situation is similar (but a bit cleaner):

irb(main):001:0> Object.ancestors
=> [Object, Kernel, BasicObject]
irb(main):002:0> Object.included_modules
=> [Kernel]
irb(main):011:0> Object.superclass
=> BasicObject
irb(main):011:0> BasicObject.superclass
=> nil
irb(main):011:0> BasicObject.included_modules
=> []
like image 985
Sam Saffron Avatar asked Sep 07 '09 23:09

Sam Saffron


People also ask

What is kernel module in Ruby?

The Object and Kernel classes are the root of all Ruby class and object functionality. Object is the base class that all Ruby classes inherit from. The Kernel module is included by the Object class and contains methods that can be used in all classes.

What is a subclass in Ruby?

Sub class: This is the class that is derived from the parent class. It is also known as a subclass or derived class or child class. You can also add its own objects, methods, along with the base class methods and objects, etc. Note: By default, every class in Ruby has a Super class.

Can you nest classes in Ruby?

Nesting class definitions in Ruby is a matter of preference, but it serves a purpose in the sense that it more strongly enforces a contract between the two classes and in doing so conveys more information about them and their uses.

How do you extend a class in Ruby?

[extend] - will add the extended class to the ancestors of the extending classes' singleton class. Other words extend mix the module's functionality into class and makes these methods available to the class itself. [super] - is used for overridden method call by the overriding method.


2 Answers

Object does not inherit from Kernel, it is the final superclass (in Ruby 1.8). The result of the #ancestors method comprises of superclasses and included modules. Specifically, in the order they are looked up for any particular call.

like image 171
Gareth Avatar answered Sep 28 '22 15:09

Gareth


When you include a module in a class it becomes part of its inheritance hierarchy. Therefore the by including Kernel Object.ancestors will include (no pun intended) Kernel. In ruby versions < 1.9 Object is at the top of the hierarchy so it has no superclass

like image 40
ennuikiller Avatar answered Sep 28 '22 17:09

ennuikiller