Ruby object model
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
num.object_id
chr = 'a'
chr.object_id
# classes are also objects
class.object_id
# Even methods are objects
method = num.method(:times)
method.object_id
# 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(:+)
plus.object_id
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 = B.new
B.class
B.ancestors
B.superclass
# modules do not fall in `superclass`
# which class does this method come from?
class A
def new_method
print “new method”
end
end
class B < A; end
b= B.new
b.new_method
> b.method :new_method
=> #<Method: B(A)#new_method>
“what instance variables does this object have?”
b.instance_variables
# []
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”
end
end
A.singleton_methods
# [:some_method]
A.some_method
a=A.new
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.