Ruby Object Model : Class and Object
To learn about the Ruby's built-in Class and Object.
Let's take a look at user defined classes.
class Car def drive puts 'driving...' end end c = Car.new c.drive
This prints 'driving...'.
We created an instance of our car class and called the drive method.
Everything in Ruby is an object. Even the class Car we defined is an object. So if that is the case then the Car class must be an instance of some class. What is that class?
class Car end p Car.class
This prints 'Class'. So the Car class is an instance of a class called Class.
The Class is Ruby's builtin class that provides the new method that we can use to instantiate the car object.
This prints [:allocate, :new, :superclass]. As a developer you will not call allocate method. You will use the new and superclass methods.
When you use the language keyword 'class', Ruby does something like this:
Car = Class.new
Let's print the class of Car.
This prints Class. Since Car is an object you can call the instance method 'new' like this:
car = Car.new
as in step 1. Because new is an instance method provided by Ruby's built-in class called Class.
Let's create a subclass:
class Beetle < Car end p Beetle.class
This prints 'Class'. Our new Beetle class also has class 'Class' from which it gets the methods such as new, superclass and allocate.
So what is the superclass of Beetle?
This prints Car. This is obvious since we defined Beetle to be subclass of Car. How about the Car class?
This prints : Object. The class Object is Ruby's built-in class. It comes into picture when you consider the inheritance hierarchy.
This is implicit. So, no need to say:
class Car < Object end p Car.class
In the previous article, we saw the value of self.class is Object. So we can also do this:
class Car < self.class end p Car.superclass
This prints 'Object'.
This makes the following code run just fine.
class Car < self.class def drive puts 'driving...' end end c = Car.new c.drive
There is no need to explicitly specify the superclass in this case. But, that's what is going on behind the scenes.
In this article, we explored how everything is an object in Ruby. All objects are instances of the Ruby's built-in class called Class. The Ruby built-in Object comes into play in the inheritance hierarchy.
Ace the Technical Interview
- Easily find the gaps in your knowledge
- Get customized lessons based on where you are
- Take consistent action everyday
- Builtin accountability to keep you on track
- You will solve bigger problems over time
- Get the job of your dreams
Take the 30 Day Coding Skills Challenge
Gain confidence to attend the interview