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


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

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]

Object's built-in properties

Every object has some built-in properties :- [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]

  • A reference to the object's immediate class, the MRI interpreter stores this in a field named "klass" and you may see the term "klass" show up in Ruby-land a lot for that reason. For an object that has an meta-class this is a pointer to the meta-class
  • A hash table of instance variables
  • A set of flags (taint etc.)

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 then invokes the greeting method is created which prints the string.


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

  • 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. [references]
  • 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.
  • Ruby provides specific 'callback' methods that are called when certain aspects of the object model are changed – such as method added or class created. [references]
  • 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 “equivalent” C or C++ code.
  • Ruby does not support multiple inheritance directly (though it introduces the concept of mixins.)
  • It gets confusing for dealing with classes because they are also objects.
  • One cannot discover whether a method within an object works or not until runtime.
  • There are only two container types for the objects to use : arrays and hashes.

See Also :


References


External Links