CSC/ECE 517 Fall 2013/ch1 1w14 st

From Expertiza_Wiki
Jump to navigation Jump to search

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: code

1234.7643.class  # Diplays the class to which the object 1234.7643 belongs. 

code

Output : code => Float code

Example 2 : code "Hello".reverse.upcase.length # Performs the reverse, upcase and length operation sequentially on the string object.

code

Output : code => 5

code

Ruby objects can also handle more than 1 methods at a time. Example 3 :

code a=[1,4,5,3,2] a.reverse.sort #reverses first to [2,3,5,4,1] and then sorts code

Output : code = > [1,2,3,4,5] code

Diagramatic Representation

Let us consider the following Ruby code snippet. code 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)

code

The object Hierarchy of the above code will be :-

File:C:\Users\Satvik\Desktop\OOLS\Wiki\Images\RubyObjectModel.jpg

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]

Objects

Object's built-in properties

Conceptual Components

Classes


Object Relationships

Superclass/Subclass relationship

Modules and Mixins


Comparision with other Object-Oriented languages

Comparision with java

Comparision with C++

...


Advantages of the Ruby Object Model


Disadvantages of the Ruby Object Model


See Also :


References


External Links