Shiva Bhusal
Shiva's Blog


Shiva's Blog


Ruby object model

Shiva Bhusal's photo
Shiva Bhusal
·Dec 28, 2019·

2 min read

Play this article

Object Introduction

Object is the base of the idea of Object Oriented Programming. Object is the mapping of real world objects or resources in to the digital paradigm.

Ruby is a true object oriented language because everything in Ruby is an object. Objects are the first-class citizens of the Ruby world. Even language constructs such as classes, instance variables, methods and modules are also objects. They live in a system known as Object Model. What do you think an object is? It’s just a bunch of instance variables, plus a link to a class.

# numbers are objects
num  = 1

chr = 'a'

# classes are also objects

# Even methods are objects
method = num.method(:times)

# operators are also objects
# actually they are methods defined in an object and which are also objects
# see all the methods `num.methods`
plus = num.method(:+)

Object Model

So basically, Object Model is a world or system where all these language constructs live together. Object Model is where you will find answers to the questions like “which class does this method come from?” , “what happens when I inherit this class?” and “what instance variables does this object have?”

class A; end
class B < A; end

B =
# modules do not fall in `superclass`

# which class does this method come from?
class A
  def new_method
     print “new method”

class B < A; end

> b.method :new_method
=> #<Method: B(A)#new_method>

“what instance variables does this object have?”
# []

Introduction to Class

The object’s methods don’t live in the object—they live in the object’s class, where they’re called the instance methods of the class.

What’s a class?

It’s just an object (an instance of Class), plus a list of instance methods and a link to a superclass. Class is a subclass of Module, so a class is also a module.

Like any object, a class has its own methods, such as new( ) and other you define. These are instance methods of the Class class. They are also called class-methods. You define these methods using self. prefix.

# reference
class A
    # this method is local to this particular class
    # other descendants of the Class class don’t have it
    # this is singleton method
    def self.some_method
        print “some method”

# [:some_method]

a.some_method # is not defined

Also like any object, classes must be accessed through references. You already have a constant reference to each class i.e. the class’s name.

Share this