CSC/ECE 517 Fall 2013/ch1 1w14 st: Difference between revisions

From Expertiza_Wiki
Jump to navigation Jump to search
No edit summary
 
(88 intermediate revisions by 2 users not shown)
Line 1: Line 1:
= '''RUBY OBJECT MODEL''' =
=Ruby Object Model=
----
 
"''In [http://en.wikipedia.org/wiki/Ruby_(programming_language) Ruby], everything is an [http://en.wikipedia.org/wiki/Object_(computer_science) object]!''" is one of the most common phrases in the Ruby [http://en.wikipedia.org/wiki/Computer_programming programming] world. This is indeed a very unique feature of Ruby. This article will help us [http://wiki.expertiza.ncsu.edu/index.php/CSC/ECE_517_Fall_2013/ch1_1w14_st#Understanding_the_Ruby_Object_Model understand the ruby object model], speak about it's [http://wiki.expertiza.ncsu.edu/index.php?title=CSC/ECE_517_Fall_2013/ch1_1w14_st#Comparison_with_other_Object-Oriented_languages comparison to object models of other programming languages] and explain it's [http://wiki.expertiza.ncsu.edu/index.php?title=CSC/ECE_517_Fall_2013/ch1_1w14_st#Advantages_of_the_Ruby_Object_Model advantages] and [http://wiki.expertiza.ncsu.edu/index.php?title=CSC/ECE_517_Fall_2013/ch1_1w14_st#Disadvantages_of_the_Ruby_Object_Model disadvantages].


"''In [http://en.wikipedia.org/wiki/Ruby_(programming_language) Ruby], everything is an [http://en.wikipedia.org/wiki/Object_(computer_science) 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 [http://en.wikipedia.org/wiki/Object_model Object-model], it's components, comparison to object models of other [http://en.wikipedia.org/wiki/Programming_languages programming languages] along with it's advantages and disadvantages.
----




__TOC__
__TOC__
==Understanding the Ruby Object Model==
Ruby is distinct to other [http://en.wikipedia.org/wiki/Object-oriented_programming object-oriented] programming languages in a way that it recognizes all of it's basic constructs ([http://en.wikipedia.org/wiki/Variable_(computer_science) 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>https://www.ruby-lang.org/en/about</ref>


In many languages, numbers and other [http://en.wikipedia.org/wiki/Primitive_data_type primitive data-types] are not objects. Ruby’s pure object-oriented approach can be illustrated by the following examples that add [http://en.wikipedia.org/wiki/Method_(computer_programming) methods] to numbers and strings.
=Understanding the Ruby Object Model=
Ruby is distinct to other [http://en.wikipedia.org/wiki/Object-oriented_programming object-oriented] programming languages in a way that it is purely object-oriented, meaning it recognizes all of it's basic constructs as [http://en.wikipedia.org/wiki/Object_(computer_science) objects]. Everything that we manipulate and  even the results of the manipulations are also objects.
 
In an [http://en.wikipedia.org/wiki/Object-oriented_programming object-oriented] code, you look forward to model concepts from the real world in your code. For example, in a ''Theatre'', the concept of a "movie" is defined as a [http://en.wikipedia.org/wiki/Class_(computer_programming) class] and is a combination of states(e.g name of the movie) and [http://en.wikipedia.org/wiki/Method_(computer_programming) methods] that use that state(e.g play the movie). We can create [http://en.wikipedia.org/wiki/Instance_(computer_science) instances] of these classes, known as objects. For example, in the above example the instances would be the various movies.
 
In Ruby, these objects are created a special method called a [http://en.wikipedia.org/wiki/Constructor_(object-oriented_programming) ''constructor''], a special method associated with a [http://en.wikipedia.org/wiki/Class_(computer_programming) class]. The standard constructor is called ''new''.
 
  movie1 = Movie.new("ABC PQR")
  movie2 = Movie.new("XYZ ABCD")
 
These instances are derived from the same class, but have unique characteristics. Every object has a unique ''object identifier'' and define instance variables that are unique to each instance, like "name" in our example.
You can define instance methods within each class. A method is a chunk of functionality that may be called from within a class or outside it, depending on the accessibility constraints.
 
Whenever you call a method on an object, the [http://en.wikipedia.org/wiki/Interpreter_(computing) interpreter] first looks through the object’s instance methods to check if that particular method exists. If the interpreter finds the method, it will be executed but if that particular method does not exist, the interpreter will pass the request up the hierarchy to the object’s class.
 
If the interpreter is not able to find the method anywhere in the hierarchy, it will go back to the object and call method_missing(). Again, the interpreter will look for method_missing() in the object’s methods, then the object’s class’s instance methods, following the hierarchy until it reaches the Object class where method_missing() is defined  and will raise a NoMethodError error. To change the default behavior, method_missing() can be defined within the class.
 
'''Example:'''
  class Sample
    def method_missing(name, *args)
      puts "#{name} was called with arguments: #{args.join(',')}"
    end
  end
m = Sample.new
m.method1("one", "two")
 
There is no [http://en.wikipedia.org/wiki/Method_(computer_programming) method] named method1() within our class that we are trying to call. here, we don’t see the usual NoMethodError,and we see the name of the methods and their [http://en.wikipedia.org/wiki/Arguments arguments], just like we defined in method_missing().
 
In many languages, numbers and other [http://en.wikipedia.org/wiki/Primitive_data_type primitive data-types] are not objects. Ruby’s pure object-oriented approach can be illustrated by the following examples that have numbers and [http://en.wikipedia.org/wiki/String_(computer_science) strings] calling in-built [http://en.wikipedia.org/wiki/Method_(computer_programming) methods].  


  ''' Example: '''   
  ''' Example: '''   
     1234.7643.class  ''# Diplays the class to which the object 1234.7643 belongs.''  
     1234.7643.class  ''# Displays the class to which the object 1234.7643 belongs.''  
   '''Output :'''   
   '''Output :'''   
     => Float  
     => Float  


Ruby objects can also handle more than one methods at a time. Let's take the following examples :
Ruby objects can also handle more than one methods at a time by writing them in a chain. Let's take the following examples :


  ''' Example:'''  
  ''' Example:'''  
Line 29: Line 54:
   '''Output:'''
   '''Output:'''
       = > [1,2,3,4,5]   
       = > [1,2,3,4,5]   
In the above examples the thing before the period is called the ''receiver'', and the name after the period is the method to be invoked.
It's worth noting here a major difference between Ruby and most other languages:
'''In JAVA''': To find the absolute value of a number, we can a separate function and pass the value of that number in that function.
Number = Math.abs(number)  // Java Code
'''In RUBY''': The ability to determine the absolute value is built into numbers(which are also objects) internally.
number = number.abs      # Ruby Code
This is the reason behind why Ruby is called a purely object oriented language.


===Diagramatic Representation===
===Diagramatic Representation===
Line 47: Line 84:




The object [http://en.wikipedia.org/wiki/Hierarchy Hierarchy] of the above code will be :-
The object Hierarchy of the above code will be :-


[[File:RubyObjectModel.jpg]]
[[File:RubyObjectModel.jpg]]
Line 55: Line 92:




In the above diagram, the objects car, truck and bike are [http://en.wikipedia.org/wiki/Instance_(computer_science) instances] of the [http://en.wikipedia.org/wiki/Class_(computer_programming) 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.  
In the above diagram, the objects car, truck and bike are [http://en.wikipedia.org/wiki/Instance_(computer_science) instances] of the [http://en.wikipedia.org/wiki/Class_(computer_programming) class] Vehicle. Vehicle in itself is an [http://en.wikipedia.org/wiki/Instance_(computer_science) 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 [http://en.wikipedia.org/wiki/Inheritance_(object-oriented_programming) 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> http://ruby-doc.org/core-1.9.3/BasicObject.html </ref>
Object [http://en.wikipedia.org/wiki/Inheritance_(object-oriented_programming) 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> http://ruby-doc.org/core-1.9.3/BasicObject.html </ref>


===Objects===
===Objects===
An object is an instance of a class. It has properties like any physical object in the real-world. In Ruby, everything is an object. To simply explain what an “object” is; it’s a thing that you send a message to. All the action in Ruby happens because you send a message to an object. In order for an object to respond meaningfully to this message, it must possess internal knowledge of the message — a series of computational steps saying what should happen when a particular message arrives, which in Ruby, is done with the help of  a method. To send a particular message to an object is to call that method of the object. <ref>
An object is an instance of a class. It has properties like any physical object in the real-world. In Ruby, everything is an object. To simply explain what an “object” is; it’s a thing that you send a [http://en.wikipedia.org/wiki/Message_passing message] to. All the action in Ruby happens because you send a message to an object. In order for an object to respond meaningfully to this message, it must possess internal knowledge of the message — a series of computational steps saying what should happen when a particular message arrives, which in Ruby, is done with the help of  a method. To send a particular message to an object is to call that method of the object. <ref>
http://www.apeth.com/rubyIntro/justenoughruby.html#theobjectorientedstructureofruby </ref>
http://www.apeth.com/rubyIntro/justenoughruby.html#theobjectorientedstructureofruby </ref>


====Object's built-in properties====
====Object's built-in properties====
Every object has some built-in properties :- <ref> http://www.slideshare.net/cchamnap/ruby-object-model-4978263 </ref>
Every object has some built-in properties :-  


* ''' object_id  '''
* ''' object_id  '''
Line 77: Line 114:
respond_to? returns true if the object responds to a given method, else if the method is not defined, respond_to_missing? method is called and the result is returned.
respond_to? returns true if the object responds to a given method, else if the method is not defined, respond_to_missing? method is called and the result is returned.
If the method is not implemented, false is returned.
If the method is not implemented, false is returned.
[http://en.wikipedia.org/wiki/Private_method#Member_accessibility Private and protected methods] are included in the search only if the optional second parameter evaluates to true.
[http://en.wikipedia.org/wiki/Private_method#Member_accessibility Private and protected methods] are included in the search only if the optional second [http://en.wikipedia.org/wiki/Parameter_(computer_programming) parameter] evaluates to true.
   
   
   '''Syntax:'''  respond_to?(symbol, include_all=false or true[optional])
   '''Syntax:'''  respond_to?(symbol, include_all=false or true[optional])
Line 86: Line 123:
   
   
* '''send '''  
* '''send '''  
Send is a very important concept in the Ruby object model as almost all actions in Ruby, atleast conceptually, boils down to sending a message to an object.
Send method can be used on any object to invoke a message handler. Additionally, Ruby makes it easier to express messages as we don’t necessarily need to use the send method, we can just use the shortcut ‘.’ (dot) operator.
Send method can be used on any object to invoke a message handler. Additionally, Ruby makes it easier to express messages as we don’t necessarily need to use the send method, we can just use the shortcut ‘.’ (dot) operator.
   
   
Line 129: Line 168:
Conceptually, Ruby objects consists of the following: <ref> http://www.hokstad.com/ruby-object-model </ref>
Conceptually, Ruby objects consists of the following: <ref> http://www.hokstad.com/ruby-object-model </ref>


* A reference to the object's immediate superclass in the object model hierarchy.
* A reference to the object's immediate [http://en.wikipedia.org/wiki/Superclass_(computer_science)#Subclasses_and_superclasses superclass] in the object model hierarchy.
* A [http://en.wikipedia.org/wiki/Hash_table hash table] of all the associated instance variables.
* A [http://en.wikipedia.org/wiki/Hash_table hash table] of all the associated instance variables.
* A set of [http://en.wikipedia.org/wiki/Flag_word flags].
* A set of [http://en.wikipedia.org/wiki/Flag_word flags].
Line 135: Line 174:
===Classes===
===Classes===


Class is an object of the class ''“Class”''. Classes are defined in Ruby using the '''class''' [http://en.wikipedia.org/wiki/Keyword_(computer_programming) keyword] followed by a name. The name of the class must begin with a capital letter. In case of more than one word in the class name, the first letter of every word must begin with a capital letter ([http://en.wikipedia.org/wiki/CamelCase CamelCase]). The class definition may contain method, class variable, and instance variable declarations as well as calls to methods that execute in the class context at read time, such as '''''attr_accessor'''''. The class declaration is terminated by the end keyword.
Class is an object of the class ''"Class"''. Classes are defined in Ruby using the ''class'' [http://en.wikipedia.org/wiki/Keyword_(computer_programming) keyword] followed by a name. The name of the class must begin with a capital letter ([http://en.wikipedia.org/wiki/CamelCase CamelCase]). The class definition may contain method, class variable, and instance variable declarations as well as calls to methods that execute in the class context at read time, such as ''attr_accessor''. The class declaration is terminated by the end keyword.


  '''Example:'''
  '''Example:'''
Line 154: Line 193:
----
----


==Object Relationships==
=Object Relationships=
===Superclass/Subclass Relationship===
===Superclass/Subclass Relationship===
'''Inheritance'''
'''Inheritance'''


Inheritance allows you to create a class that is a refinement or specialization of another class. The specialized class is called the sub class and the parent from which it inherits these properties is called the super class. The major use of inheritance is re-usability of the code.
[http://en.wikipedia.org/wiki/Inheritance_(object-oriented_programming) Inheritance] allows you to create a class that is a refinement or specialization of another class. The specialized class is called the [http://en.wikipedia.org/wiki/Superclass_(computer_science)#Subclasses_and_superclasses subclass] and the parent from which it inherits these properties is called the [http://en.wikipedia.org/wiki/Superclass_(computer_science)#Subclasses_and_superclasses superclass]. The major use of inheritance is re-usability of the code.


  Syntax: Sub-Class < Super-Class
  Syntax: Sub-Class < Super-Class
Line 180: Line 219:
     Method 2
     Method 2


Thus, the sub-class in this example,'SubClass' inherits 'method_1' from its super-class, which is 'SuperClass',thereby, inheriting the properties of the super-class and extending its own properties.
Thus, the sub-class in this example,'SubClass' inherits 'method_1' from its super-class, which is 'SuperClass',thereby, inheriting the properties of the super-class and [http://en.wikipedia.org/wiki/Inheritance_(object-oriented_programming) extending] its own properties.


----
----


== Comparision with other Object-Oriented languages ==
= Comparison with other Object-Oriented languages =
===Comparison with Java===
===Comparison with Java===


Java objects are similar to Ruby objects in some ways :- <ref name=ref1> https://www.ruby-lang.org/en/documentation/ruby-from-other-languages/to-ruby-from-java/ </ref>
Java objects are similar to Ruby objects in some ways :- <ref name=ref1> https://www.ruby-lang.org/en/documentation/ruby-from-other-languages/to-ruby-from-java/ </ref>


* The [http://en.wikipedia.org/wiki/Garbage_collection_(computer_science) garbage collector] takes care of memory handling.
* The [http://en.wikipedia.org/wiki/Garbage_collection_(computer_science) garbage collector] takes care of memory handling of unused objects.
* Objects are strongly typed.
* Objects are strongly typed.
* Both Ruby and java objects have public, private, and protected access specifiers for methods.
* Both Ruby and java objects have public, private, and protected [http://en.wikipedia.org/wiki/Access_modifiers access specifiers] for methods defined within objects.


The properties of a java object differ from that of a Ruby object in the following way :- <ref name=ref1 />
The properties of a java object differ from that of a Ruby object in the following way :- <ref name=ref1 />
Line 201: Line 240:
| Classes in java are pure definitions of set of inter-related variables and methods. They do not take memory. || Class itself is an object in Ruby and has memory.  
| Classes in java are pure definitions of set of inter-related variables and methods. They do not take memory. || Class itself is an object in Ruby and has memory.  
|-
|-
| Java supports inheritance of classes using the 'extends' keyword. || In Ruby, we use the '<' symbol to show inheritance.
| Java supports [http://en.wikipedia.org/wiki/Inheritance inheritance] of classes using the 'extends' keyword. || In Ruby, we use the '<' symbol to show inheritance.
|-
|-
| Java uses interfaces for defining empty methods which are later handled by concrete class objects. || Ruby does not support interfaces.
| Java uses [http://en.wikipedia.org/wiki/Interfaces_(computer_science) interfaces] for defining empty methods which are later handled by [http://en.wikipedia.org/wiki/Concrete_class#Abstract_and_Concrete concrete class] objects. || Ruby does not support interfaces.
|-
|-
| In java, constructor is used as the default method.  || In Ruby, the initialize method solves this purpose.
| In java, [http://en.wikipedia.org/wiki/Constructor_(object-oriented_programming) constructor] is used as the default method.  || In Ruby, the initialize method solves this purpose.
|-
|-
| Java uses the (.) operator to access class variables. || Ruby on the other hand, uses (.) variable to call methods on an object.
| Java uses the (.) operator to access class variables. || Ruby on the other hand, uses (.) variable to call methods on an object.
|-
|-
| String objects in Java are immutable (state cannot be changed) || In Ruby, string objects are mutable.
| String objects in Java are [http://en.wikipedia.org/wiki/Immutable_object immutable] (state cannot be changed) || In Ruby, string objects are mutable.
|-  
|-  
|}
|}


===Comparision with C++===   
===Comparison with C++===   


Typically, C++ objects are [http://en.wikipedia.org/wiki/Instance_(computer_science) instances] of the classes defined with member [http://en.wikipedia.org/wiki/Variable_(computer_science) variables] and [http://en.wikipedia.org/wiki/Method_(computer_programming) methods]. Let us see how the object properties of Ruby differ from those of C++. <ref> http://www.objs.com/x3h7/cplus.htm </ref> <ref name="ref2"> https://www.ruby-lang.org/en/documentation/ruby-from-other-languages/to-ruby-from-c-and-cpp/ </ref>
Typically, C++ objects are [http://en.wikipedia.org/wiki/Instance_(computer_science) instances] of the classes defined with member [http://en.wikipedia.org/wiki/Variable_(computer_science) variables] and [http://en.wikipedia.org/wiki/Method_(computer_programming) methods]. Let us see how the object properties of Ruby differ from those of C++. <ref> http://www.objs.com/x3h7/cplus.htm </ref> <ref name="ref2"> https://www.ruby-lang.org/en/documentation/ruby-from-other-languages/to-ruby-from-c-and-cpp/ </ref>
Line 221: Line 260:
! Objects in C++  !! Objects in Ruby  
! Objects in C++  !! Objects in Ruby  
|-
|-
|    In C++, class defines only the blueprint of variables and mehods associated to them. It does not have memory.    ||    In ruby, classes are instances(objects) of the class 'Class'.  
|    In C++, class defines only the blueprint of variables and methods associated to them. It does not have memory.    ||    In ruby, classes are instances(objects) of the class 'Class'.  
|-
|-
| We need to declare the types for C++ objects. (statically-typed language) || Ruby objects take the type of the value they are assigned to. (dynamically typed)
| We need to declare the types for C++ objects. (statically-typed language) || Ruby objects take the type of the value they are assigned to. (dynamically typed)
|-
|-
| Behaviour of an object is defined by it's member methods that are programmed by the user. || Every object in Ruby has a set of predefined methods on itself that can be accessed by using 'object.methods' clause.  
| Behavior of an object is defined by it's member methods that are programmed by the user. || Every object in Ruby has a set of predefined methods on itself that can be accessed by using 'object.methods' clause.  
|-  
|-  
| In C++, initialization of instance variables of an object is done by a method named 'constructor'. || In Ruby, 'initialize' method is used for the same purpose.
| In C++, initialization of instance variables of an object is done by a method named 'constructor'. || In Ruby, 'initialize' method is used for the same purpose.
|-  
|-  
| A C++ class is a compile-time entity. || A ruby class is a run-time entity.
| A C++ class is a [http://en.wikipedia.org/wiki/Compile_time compile-time] entity. || A ruby class is a [http://en.wikipedia.org/wiki/Run_time_(program_lifecycle_phase) run-time] entity.
|-  
|-  
| An abstract class in C++ has only definition. No objects of this class can be created.|| Ruby doesn't support the concept of abstract classes as a class is an instance in itself.
| An abstract class in C++ has only definition. No objects of this class can be created.|| Ruby doesn't support the concept of abstract classes as a class is an instance in itself.
|-
| Variables in C++ refer to data members of corresponding classes. || There’s no explicit references in Ruby. Every variable is a name for some object.
|-
|-
| In C++, 'this' keyword is used by object to reference itself. || In Ruby, self is used for this purpose.
| In C++, 'this' keyword is used by object to reference itself. || In Ruby, self is used for this purpose.
|-
|-
| We have to include all the required functionality while defining the class. || We can reopen a class at anytime and add functionality. 
|C++ does not need a base class as it supports [http://en.wikipedia.org/wiki/Generic_programming generic programming]. || All classes in Ruby however, are instances of the 'Object' class which in turn is a sub-class of 'BasicObject' class.
|-
|C++ does not need a base class as it supports generic programming. || All classes in Ruby however, are instances of the 'Object' class which in turn is a sub-class of 'BasicObject' class.
|}
|}


Line 254: Line 289:
----
----


==Advantages of the Ruby Object Model==
=Advantages of the Ruby Object Model=


* All objects are created at [http://en.wikipedia.org/wiki/Run_time_(program_lifecycle_phase) run time]. There is no [http://en.wikipedia.org/wiki/Compile_time compile time] in Ruby.
* All objects are created at [http://en.wikipedia.org/wiki/Run_time_(program_lifecycle_phase) run time]. There is no [http://en.wikipedia.org/wiki/Compile_time compile time] in Ruby.
Line 261: Line 296:
* Ruby provides callback methods that are called when certain aspects of the object model are changed – such as method added or class created. <ref> http://mastercontrolknob.wordpress.com/2013/01/13/ruby-object-model-part-1-basics/ </ref>
* Ruby provides callback methods that are called when certain aspects of the object model are changed – such as method added or class created. <ref> http://mastercontrolknob.wordpress.com/2013/01/13/ruby-object-model-part-1-basics/ </ref>
* Ruby Objects are strongly typed.  
* Ruby Objects are strongly typed.  
* If we notice, ruby methods within ruby objects do not require paranthesis. We can end a looping construct or a method within an object using the 'end' keyword. This reduces a lot of confusion in placing the opena
* If we notice, ruby methods within ruby objects do not require paranthesis. We can end a looping construct or a method within an object using the 'end' keyword. This reduces a lot of confusion in placing the open and close braces.
* Unlike in other programming languages, Ruby provides more flexibility to modify features of it's standard objects. Eg :- [http://en.wikipedia.org/wiki/String_(computer_science) String] objects in Ruby are mutable ie., Ruby defines upcase, lowcase and swapcase methods on them.
* Unlike in other programming languages, Ruby provides more flexibility to modify features of it's standard objects. Eg :- [http://en.wikipedia.org/wiki/String_(computer_science) String] objects in Ruby are mutable ie., Ruby defines upcase, lowcase and swapcase methods on them.
* An object in Ruby can identify it's own class when asked by the user using the '.class' method.
* An object in Ruby can identify it's own class when asked by the user using the '.class' method.
Line 269: Line 304:
----
----


==Disadvantages of the Ruby Object Model==
=Disadvantages of the Ruby Object Model=


* Though Ruby programs can be written quickly, there is too much load being shouldered at [http://en.wikipedia.org/wiki/Run_time_(program_lifecycle_phase) runtime]. Hence, we may expect our Ruby code to execute much more slowly than in other object-oriented languages.
* Though Ruby programs can be written quickly, there is too much load being shouldered at [http://en.wikipedia.org/wiki/Run_time_(program_lifecycle_phase) runtime]. Hence, we may expect our Ruby code to execute much more slowly than in other object-oriented languages.
Line 280: Line 315:
----
----


==See Also  ==
=See Also  =


[http://en.wikipedia.org/wiki/Ruby_(programming_language) Ruby programming Language] <br>
[http://en.wikipedia.org/wiki/Ruby_(programming_language) Ruby programming Language] <br>
[http://www.ruby-doc.org/docs/ProgrammingRuby/html/tut_classes.html Objects and Classes in Ruby] <br>
[http://en.wikipedia.org/wiki/Plain_Old_Java_Object Java Objects]<br>
[http://en.wikipedia.org/wiki/Plain_Old_Java_Object Java Objects]<br>
[http://fhwang.net/2004/11/14/Coming-to-Ruby-from-Java Coming to Ruby from Java]<br>
[http://en.wikipedia.org/wiki/Plain_Old_C%2B%2B_Object C++ Objects]<br>
[http://en.wikipedia.org/wiki/Plain_Old_C%2B%2B_Object C++ Objects]<br>
[http://en.wikipedia.org/wiki/Object_model Object Model]<br>
[http://en.wikipedia.org/wiki/Object_model Object Model]<br>
[http://en.wikipedia.org/wiki/Document_object_model Document Object Model(DOM)]<br>
[http://en.wikipedia.org/wiki/Document_object_model Document Object Model(DOM)]<br>
[http://staff.science.uva.nl/~heck/JAVAcourse/ch3/s1.html Class Hierarchies] <br>
[http://stackoverflow.com/questions/4688467/class-vs-object-hierarchies Understanding the difference between an object and a class hierarchy]


----
----


== References ==
= References =
<references/>
<references/>
----
----

Latest revision as of 03:05, 25 September 2013

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 help us understand the ruby object model, speak about it's comparison to object models of other programming languages and explain it's advantages and disadvantages.


Understanding the Ruby Object Model

Ruby is distinct to other object-oriented programming languages in a way that it is purely object-oriented, meaning it recognizes all of it's basic constructs as objects. Everything that we manipulate and even the results of the manipulations are also objects.

In an object-oriented code, you look forward to model concepts from the real world in your code. For example, in a Theatre, the concept of a "movie" is defined as a class and is a combination of states(e.g name of the movie) and methods that use that state(e.g play the movie). We can create instances of these classes, known as objects. For example, in the above example the instances would be the various movies.

In Ruby, these objects are created a special method called a constructor, a special method associated with a class. The standard constructor is called new.

 movie1 = Movie.new("ABC PQR")
 movie2 = Movie.new("XYZ ABCD") 

These instances are derived from the same class, but have unique characteristics. Every object has a unique object identifier and define instance variables that are unique to each instance, like "name" in our example. You can define instance methods within each class. A method is a chunk of functionality that may be called from within a class or outside it, depending on the accessibility constraints.

Whenever you call a method on an object, the interpreter first looks through the object’s instance methods to check if that particular method exists. If the interpreter finds the method, it will be executed but if that particular method does not exist, the interpreter will pass the request up the hierarchy to the object’s class.

If the interpreter is not able to find the method anywhere in the hierarchy, it will go back to the object and call method_missing(). Again, the interpreter will look for method_missing() in the object’s methods, then the object’s class’s instance methods, following the hierarchy until it reaches the Object class where method_missing() is defined and will raise a NoMethodError error. To change the default behavior, method_missing() can be defined within the class.

Example:
  class Sample
   def method_missing(name, *args)
     puts "#{name} was called with arguments: #{args.join(',')}"
   end
  end
m = Sample.new
m.method1("one", "two") 

There is no method named method1() within our class that we are trying to call. here, we don’t see the usual NoMethodError,and we see the name of the methods and their arguments, just like we defined in method_missing().

In many languages, numbers and other primitive data-types are not objects. Ruby’s pure object-oriented approach can be illustrated by the following examples that have numbers and strings calling in-built methods.

 Example:   
    1234.7643.class   # Displays the class to which the object 1234.7643 belongs. 
 Output :  
    => Float 

Ruby objects can also handle more than one methods at a time by writing them in a chain. Let's take the following examples :

 Example: 
    "Hello".reverse.upcase.length   # Performs the reverse, upcase and length operation sequentially on the string object.
 Output:
    => 5
  Example:
     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]  

In the above examples the thing before the period is called the receiver, and the name after the period is the method to be invoked.

It's worth noting here a major difference between Ruby and most other languages:

In JAVA: To find the absolute value of a number, we can a separate function and pass the value of that number in that function.

Number = Math.abs(number)   // Java Code

In RUBY: The ability to determine the absolute value is built into numbers(which are also objects) internally.

number = number.abs       # Ruby Code

This is the reason behind why Ruby is called a purely object oriented language.


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

Fig.1 An illustration of the Ruby Object Model<ref> http://ruby-doc.org/core-1.9.3/Class.html </ref>


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> http://ruby-doc.org/core-1.9.3/BasicObject.html </ref>

Objects

An object is an instance of a class. It has properties like any physical object in the real-world. In Ruby, everything is an object. To simply explain what an “object” is; it’s a thing that you send a message to. All the action in Ruby happens because you send a message to an object. In order for an object to respond meaningfully to this message, it must possess internal knowledge of the message — a series of computational steps saying what should happen when a particular message arrives, which in Ruby, is done with the help of a method. To send a particular message to an object is to call that method of the object. <ref> http://www.apeth.com/rubyIntro/justenoughruby.html#theobjectorientedstructureofruby </ref>

Object's built-in properties

Every object has some built-in properties :-

  • object_id

object_id returns an unique integer identifier for the object. This integer will be returned on all calls to id for a given object.

Example:
   day = “Tuesday”
   day.object_id
Output:
   => 19712676

  • respond_to?

respond_to? returns true if the object responds to a given method, else if the method is not defined, respond_to_missing? method is called and the result is returned. If the method is not implemented, false is returned. Private and protected methods are included in the search only if the optional second parameter evaluates to true.

 Syntax:   respond_to?(symbol, include_all=false or true[optional])
 Example: 
    @student.respond_to?('course_work')
 Explanation: The code would return true if the Student class has an course_work method on it.

  • send

Send is a very important concept in the Ruby object model as almost all actions in Ruby, atleast conceptually, boils down to sending a message to an object.

Send method can be used on any object to invoke a message handler. Additionally, Ruby makes it easier to express messages as we don’t necessarily need to use the send method, we can just use the shortcut ‘.’ (dot) operator.

  Example:
   2.send :+,3  same as   2+3   
  Output: => 5
  • methods

Returns a list of the names of public and protected methods of the object which would include all the methods accessible in the object’s ancestors.

Example:
2.methods  # displays all the methods that the object 2 can call.
Output:
 => [:to_s, :-@, :+, :-, :*, :/, :div, :%, :modulo, :divmod, :fdiv, :**, :abs, :magnitude, :==, :===,
  :<=>, :>, :>=, :<, :<=, :~, :&, :|, :^, :[], :<<, :>>, :to_f, :size, :zero?, :odd?, :even?, :succ,  
  :ord, :integer?, :upto, :downto, :times, :next, :pred, :chr, :to_i, :to_int, :floor, :ceil, 
  :truncate, :round, :gcd, :lcm, :gcdlcm, :numerator, :denominator, :to_r, :rationalize, 
  :singleton_method_added, :coerce, :i, :+@, :eql?, :quo, :remainder, :real?, :nonzero?, :step,
  :to_c,:real, :imaginary, :imag, :abs2, :arg, :angle, :phase, :rectangular, :rect, :polar, :conjugate, 
  :conj, :between?, :nil?, :=~, :!~, :hash, :class, :singleton_class, :clone, :dup, :initialize_dup, 
  :initialize_clone, :taint, :tainted?, :untaint, :untrust, :untrusted?, :trust, :freeze, :frozen?, 
  :inspect, :methods, :singleton_methods, :protected_methods, :private_methods, :public_methods, 
  :instance_variables,:instance_variable_get, :instance_variable_set, :instance_variable_defined?, 
  :instance_of?, :kind_of?, :is_a?, :tap, :send, :public_send, :respond_to?, :respond_to_missing?, 
  :extend, :display, :method, :public_method, :define_singleton_method, :object_id, :to_enum, :enum_for,
  :equal?, :!, :!=, :instance_eval, :instance_exec, :__send__, :__id__]
  • Instance Variables

Instance variables are created for each class instance and are accessible only within that instance. They are accessed using the @ operator and can be referenced by any method within the class but to access them outside of the class we use public methods which are called accessor methods.

Example:
   class Lecture
    def initialize(name, subject, duration)
      @name = name
      @subject = subject
      @duration = duration
     end
   end
Explanation:  If we take above defined class Lecture then @name, @subject and @duration are instance variables for the class Lecture.

Conceptual Components

Conceptually, Ruby objects consists of the following: <ref> http://www.hokstad.com/ruby-object-model </ref>

  • A reference to the object's immediate superclass in the object model hierarchy.
  • A hash table of all the associated instance variables.
  • A set of flags.

Classes

Class is an object of the class "Class". Classes are defined in Ruby using the class keyword followed by a name. The name of the class must begin with a capital letter (CamelCase). The class definition may contain method, class variable, and instance variable declarations as well as calls to methods that execute in the class context at read time, such as attr_accessor. The class declaration is terminated by the end keyword.

Example:
  class Example
   def greeting
     puts "Hello World!"
   end
  end
 #Using above class to create objects
object = Example.new
object.greeting

Output:
   Hello World!

The above example defines a class named ‘Example’ with a single method called ‘greeting’ . Then an object which invokes the greeting method is created which prints the string.


Object Relationships

Superclass/Subclass Relationship

Inheritance

Inheritance allows you to create a class that is a refinement or specialization of another class. The specialized class is called the subclass and the parent from which it inherits these properties is called the superclass. The major use of inheritance is re-usability of the code.

Syntax: Sub-Class < Super-Class
Example: 
class SuperClass
  def method_1
   puts “Method 1”
  end
end
class SubClass < SuperClass
  def method_2
   puts “Method 2”
  end
end
obj=SubClass.new
obj.method_1
obj.method_2
Output:
   Method 1
   Method 2

Thus, the sub-class in this example,'SubClass' inherits 'method_1' from its super-class, which is 'SuperClass',thereby, inheriting the properties of the super-class and extending its own properties.


Comparison with other Object-Oriented languages

Comparison with Java

Java objects are similar to Ruby objects in some ways :- <ref name=ref1> https://www.ruby-lang.org/en/documentation/ruby-from-other-languages/to-ruby-from-java/ </ref>

  • The garbage collector takes care of memory handling of unused objects.
  • Objects are strongly typed.
  • Both Ruby and java objects have public, private, and protected access specifiers for methods defined within objects.

The properties of a java object differ from that of a Ruby object in the following way :- <ref name=ref1 />

Objects in java Objects in Ruby
Classes in java are pure definitions of set of inter-related variables and methods. They do not take memory. Class itself is an object in Ruby and has memory.
Java supports inheritance of classes using the 'extends' keyword. In Ruby, we use the '<' symbol to show inheritance.
Java uses interfaces for defining empty methods which are later handled by concrete class objects. Ruby does not support interfaces.
In java, constructor is used as the default method. In Ruby, the initialize method solves this purpose.
Java uses the (.) operator to access class variables. Ruby on the other hand, uses (.) variable to call methods on an object.
String objects in Java are immutable (state cannot be changed) In Ruby, string objects are mutable.

Comparison with C++

Typically, C++ objects are instances of the classes defined with member variables and methods. Let us see how the object properties of Ruby differ from those of C++. <ref> http://www.objs.com/x3h7/cplus.htm </ref> <ref name="ref2"> https://www.ruby-lang.org/en/documentation/ruby-from-other-languages/to-ruby-from-c-and-cpp/ </ref>

Objects in C++ Objects in Ruby
In C++, class defines only the blueprint of variables and methods associated to them. It does not have memory. In ruby, classes are instances(objects) of the class 'Class'.
We need to declare the types for C++ objects. (statically-typed language) Ruby objects take the type of the value they are assigned to. (dynamically typed)
Behavior of an object is defined by it's member methods that are programmed by the user. Every object in Ruby has a set of predefined methods on itself that can be accessed by using 'object.methods' clause.
In C++, initialization of instance variables of an object is done by a method named 'constructor'. In Ruby, 'initialize' method is used for the same purpose.
A C++ class is a compile-time entity. A ruby class is a run-time entity.
An abstract class in C++ has only definition. No objects of this class can be created. Ruby doesn't support the concept of abstract classes as a class is an instance in itself.
In C++, 'this' keyword is used by object to reference itself. In Ruby, self is used for this purpose.
C++ does not need a base class as it supports generic programming. All classes in Ruby however, are instances of the 'Object' class which in turn is a sub-class of 'BasicObject' class.

Comparison with PHP

When we compare the Ruby object model with PHP objects, the following are some of the distinctions we make :- <ref> https://www.ruby-lang.org/en/documentation/ruby-from-other-languages/to-ruby-from-php/ </ref>

  • Because Ruby is a strongly typed language, we will have to call on special methods to convert between strings, numbers and other object types whereas this is taken care of by the language itself in PHP.
  • All arrays, hashes and similar data constructs in Ruby are objects. In PHP these are used as arguments for methods whereas in Ruby, we define methods on these objects.
  • There is no need to use separate 'Reflection' classes in Ruby as reflection is an inherent property of the object.
  • Unlike PHP, there are no interfaces or abstract classes in Ruby.
  • Variables in Ruby are themselves object references.

Advantages of the Ruby Object Model

  • All objects are created at run time. There is no compile time in Ruby.
  • Object properties can be altered during execution making it very flexible for the programmer.
  • Ruby is a much simpler language than it's other object-oriented counterparts due to the absence of certain constructs such as abstract classes and compile time nuances.
  • Ruby provides callback methods that are called when certain aspects of the object model are changed – such as method added or class created. <ref> http://mastercontrolknob.wordpress.com/2013/01/13/ruby-object-model-part-1-basics/ </ref>
  • Ruby Objects are strongly typed.
  • If we notice, ruby methods within ruby objects do not require paranthesis. We can end a looping construct or a method within an object using the 'end' keyword. This reduces a lot of confusion in placing the open and close braces.
  • Unlike in other programming languages, Ruby provides more flexibility to modify features of it's standard objects. Eg :- String objects in Ruby are mutable ie., Ruby defines upcase, lowcase and swapcase methods on them.
  • An object in Ruby can identify it's own class when asked by the user using the '.class' method.
  • It is easier to code in Ruby than in C++ or java because of the simplified syntax. Hence the term "syntactic sugar".



Disadvantages of the Ruby Object Model

  • Though Ruby programs can be written quickly, there is too much load being shouldered at runtime. Hence, we may expect our Ruby code to execute much more slowly than in other object-oriented languages.
  • Ruby does not support multiple inheritance directly (though it introduces the concept of mixins.)
  • It gets confusing when dealing with classes because they are also objects.
  • One cannot discover whether a method within an object works or not until runtime. <ref name=ref2 />
  • There are only two container types for the objects to use : arrays and hashes.



See Also

Ruby programming Language
Objects and Classes in Ruby
Java Objects
Coming to Ruby from Java
C++ Objects
Object Model
Document Object Model(DOM)
Class Hierarchies
Understanding the difference between an object and a class hierarchy


References

<references/>