CSC/ECE 517 Fall 2013/ch1 1w14 st
RUBY OBJECT MODEL
"In Ruby, everything is an object!" is one of the most common phrases in the Ruby programming world. This is indeed a very unique feature of Ruby. This article will explain, with illustrative examples, about the Ruby Object-model, it's components, comparison to object models of other programming languages along with it's advantages and disadvantages.
Understanding the Ruby Object Model
Ruby is distinct to other object-oriented programming languages in a way that it recognizes all of it's basic constructs (variables, operations, classes etc...) as objects. Every bit of information and code can be given their own properties and actions. Rules applicable to objects are relevant to all constructs of ruby. [ref] In many languages, numbers and other primitive types are not objects. Ruby’s pure object-oriented approach can be illustrated by the following examples that add methods to numbers and strings.
Example 1:
1234.7643.class # Diplays the class to which the object 1234.7643 belongs.
Output :
=> Float
Example 2 :
"Hello".reverse.upcase.length # Performs the reverse, upcase and length operation sequentially on the string object.
Output :
=> 5
Ruby objects can also handle more than 1 methods at a time. Let's take the following example :
Example 3 :
a=[1,4,5,3,2] a.reverse.sort #reverses first to [2,3,5,4,1] and then sorts
Output :
= > [1,2,3,4,5]
Diagramatic Representation
Let us consider the following Ruby code snippet.
class Vehicle def tyres(tyre_num) return tyre_num end end car=Vehicle.new() puts car.tyres(4) truck=Vehicle.new() puts truck.tyres(6) bike=Vehicle.new() puts bike.tyres(2)
The object Hierarchy of the above code will be :-
An illustration of the Ruby Object Model
In the above diagram, the objects car, truck and bike are instances of the class Vehicle. Vehicle in itself is an instance of(object of) the class 'Class'. Since in Ruby everything is an object, all the instances of the 'Vehicle' class, the Vehicle class itself and the class 'Class' are all objects of the 'Object' class. Object inherits from BasicObject. BasicObject is the parent class of all classes in Ruby. It's an explicit blank class and is used for creating object hierarchies independent of Ruby's object hierarchy. [ref]