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>https://www.ruby-lang.org/en/about</ref>

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 add methods to numbers and strings.

 Example:   
    1234.7643.class   # Diplays the class to which the object 1234.7643 belongs. 
 Output :  
    => Float 
 Example: 
    "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 one methods at a time. Let's take the following example :

  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]  

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 :- <ref> http://www.slideshare.net/cchamnap/ruby-object-model-4978263 </ref>

  • 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 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. In case of more than one word in the class name, the first letter of every word 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

Modules and Mixins


Comparision with other Object-Oriented languages

Comparison with java

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

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

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

Objects in java Objects in Ruby

Comparision 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> 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 mehods 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)
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.
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.
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.
We have to include all the required functionality while defining the class. We can reopen a class at anytime and add functionality.

...


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 opena
  • 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



See Also :

Ruby programming Language
Java Objects
C++ Objects
Object Model
Document Object Model(DOM)


References

<references/>


External Links