CSC/ECE 517 Fall 2013/ch1 1w14 st: Difference between revisions
Line 9: | Line 9: | ||
=Understanding the Ruby Object Model= | =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 objects. Everything we manipulate is an object and the results of those manipulations are themselves objects. | 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 objects. Everything we manipulate is an object and the results of those manipulations are themselves objects. | ||
When you write an object-oriented code, you look forward to model concepts from the real world in your code. During this process yuo will find categories of things that needs to be represented in code. For example, in a ''Theatre'', the concept of a "movie" could be such a category which in Ruby 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). | When you write an object-oriented code, you look forward to model concepts from the real world in your code. During this process yuo will find categories of things that needs to be represented in code. For example, in a ''Theatre'', the concept of a "movie" could be such a category which in Ruby 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). | ||
Line 59: | Line 39: | ||
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(). | 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 [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 strings calling in-built [http://en.wikipedia.org/wiki/Method_(computer_programming) 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] | |||
===Diagramatic Representation=== | ===Diagramatic Representation=== |
Revision as of 23:48, 24 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 we manipulate is an object and the results of those manipulations are themselves objects.
When you write an object-oriented code, you look forward to model concepts from the real world in your code. During this process yuo will find categories of things that needs to be represented in code. For example, in a Theatre, the concept of a "movie" could be such a category which in Ruby 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).
Once you have classes, you'll want to create instances of these classes. For example, in the above example the instances would be the various movies. The word object is used interchangeably with class instance.
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 they have unique characteristics. Every object has a unique object identifier and define instance variables that are unique to each instance, like "title" in our example.
Within each class, you can define instance methods. Each method is a chunk of functionality that may be called from whithin a class or outside it depending on the accessibility constraints.
Before going further, it is important that we understand the basics of Ruby’s Object Model and how Ruby deals with method calls.
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 can find the method, it will execute it as expected but if that particular method does not exists, it will pass the request up the chain to the object’s class. If it can’t find the method there it will continue to look in that class’s parent class, then the parent’s parent etc. up to the Object class itself.
In the end, if the interpreter is not able to find the method anywhere up the object’s chain of inheritance, it will go back to the object and call another method called method_missing(). Just like with our first method, the interpreter looks for method_missing() in the object’s methods, then the object’s class’s instance methods etc. until it reaches the Object class where method_missing() is defined and will raise a NoMethodError error. By defining method_missing() yourself within a class, it’s possible to change this default behaviour.
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]
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 veryimportant 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 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) |
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
Java Objects
C++ Objects
Object Model
Document Object Model(DOM)
References
<references/>