CSC/ECE 517 Fall 2013/ch1 1w14 st
Headline text
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]
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') Output: #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.
Syntax :
send(symbol [, args...]) → obj
Example: 2.send :+,3 Output: 5
This is same as:
Example: 2+3 Ouput:5
• method : 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 1 : 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__] http://ruby-doc.org/core-2.0.0/Object.html • 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.