CSC/ECE 517 Fall 2012/ch1b 1w55 ms

From PG_Wiki
Jump to: navigation, search

SaaS - 3.2, 3.3 - Ruby Objects and Methods



Ruby is purely an object-oriented language. In Ruby, everything is an object and every operation is a method call on some object. In contrast, hybrid languages such as C++ and Java make use of different entities like objects and primitive types. The hybrid approach yields better performance, but the pure object-oriented approach is more consistent, flexible and simpler to use.

Objects In Ruby

What is an Object?

An object is a self-contained piece of functionality that can be easily used, and re-used in an application. They serve as building blocks for a software application.

Objects consist of data variables and functions (called methods) that can be accessed and called on the object so as to perform certain tasks. These are collectively referred to as members.

Everything is an Object

Just about everything in Ruby, from numbers and strings to arrays is an object. In Ruby, we can ask any object about the methods it could respond to by calling a member function on the object.


  It considers even an integer as an object.
    It returns the entire list of methods that the “object” 57 responds to.
  Ruby considers “nil” as an object too.
    It returns ‘true’ or ‘false’ depending on whether ‘nil’ responds to the method ‘to_s’.
    (It does respond to the method and so returns ‘true’.)

In many languages, numbers and other primitive types are not objects. Ruby follows a more simplified approach which is influenced by the Smalltalk language. It involves giving methods and instance variables to all of its types. This eases one’s use of Ruby. Since Ruby is made up of objects, the rules applying to objects apply to all of Ruby.

Creation of Objects

Before understanding how we create objects, we define what is a Class.

What is a Class?

A Class defines a type of data structure. It defines the various methods and member variables used by the object and what functions they will perform. It is a way of defining common behavior for all of the objects that are of that class type. An object is nothing but an instance of a class.

Defining a Ruby class

For defining Classes, we use the keyword ‘class’ followed by the keyword ‘end’ and the class must be given a name by which it can be referenced. This name being a constant must begin with a capital letter. We can illustrate this using an example:

 class Student
   def initialize ()
   def test_method
      puts "The class is working"

Creating an object from the class

An object can be created from a class using the ‘new’ method. For example, to create an instance of a Student class we perform the following:

  student =

This creates a Student object named ‘student’. Upon the created object we can call the method ‘test_method’ by using the following:

  The class is working

Another Example:

  class Person
    attr_reader :name, :age
    def initialize(name, age)
      @name, @age = name, age
 # create 3 objects of class Person 
 p1 ="Bob", 33),
 p2 ="Chris", 16),
 p3 ="Ash", 23)


What is a Method?

In Object-Oriented Programming, we do not operate directly on the data. Rather than operating from outside the object; the objects have some understanding of how to operate on themselves. Messages are passed to an object, and those messages will generally elicit some kind of an action or meaningful reply depending on whether the object responds to that method. The tasks we are allowed to ask an object to perform (or equivalently, the messages it understands) are that object's methods.

Every operation is a method call

In Ruby, we invoke a method on an object using a dot (.) notation, just as in C++ or Java. The object on which the method performs the action is placed on the left side of the dot. Examples:

  Output: 6

Here the ‘length’ method is called upon the object “abcdef”. Basically, everything in the language is syntactic sugar for doing a method call. So the above example implies the following:


‘send’ is a method that is defined by default on every object in Ruby. Here the method ‘length’ is sent to the object “abcdef”, considering that the object “abcdef” will respond to the method ‘length’. More Examples:

  1 + 2		        => 		1.send(:+ , 2)
  my_array[4]		=>		my_array.send(:[], 4)
  my_array[3] = “foo”	=>		my_array.send(:[]=, 3, “foo”)
  my_func(z)		=>		self.send(:my_func, z)

In short, a.b means: call method ‘b’ on object ‘a’. So ‘a’ is the receiver to which you send the method call, assuming ‘a’ will respond to the method ‘b’.

Note: a.b does NOT mean that "b" is an instance variable of "a" OR "a" is some kind of data structure that has "b" as a member.

Destructive Methods

Ruby methods that modify the original copy of an object (in-place) and end in an exclamation mark are known as destructive methods. By convention, the bang(!) labels a method as dangerous.

The methods usually, perform an action and return a freshly minted object, reflecting the results of the action (capitalizing a string, sorting an array, and so on). Each method has a destructive as well as a non-destructive version. The destructive versions of the same methods perform the action, but they do so in place: Instead of creating a new object, they transform the original object.

Examples of such pairs of methods include sort/sort! for arrays, upcase/upcase! for strings, and reverse/reverse! for strings and arrays. In each case, if you call the non-destructive version of the method on the object, a new copy is created and a new object is obtained. If you call the destructive version (with ‘!’), you operate in-place on the same object to which the message is sent and the object is destructively modified. Example:

  y = y + [“foo”, :bar]
  This will create a new object which is a concatenation of ‘y’ and the [“foo”, :bar] array.


  y << [6,7] 
  will destructively modify the receiver ‘y’ and ‘y’ will become the new array [6,7].

Poetry Mode

The parentheses in method calls and hashes are always optional, not just for zero-argument calls. “Poetry mode in Ruby" is a bunch of method calls with no parentheses. It is used to simplify the method calls. Ruby prefers convention over configuration. Example:

  a.should be >= 7
  => a.should(be() >= 7)
  => a.should(be.send(:>=, 7))

Similarly parentheses in Hashes are also optional when hash is the last argument in the method call. Example:

  link_to “Edit”, :controller => ‘students’, :action => ‘edit’
  => link_to(“Edit”, {:controller => ‘students’, :action => ‘edit’})

But in case there are multiple hashes then it is always advisable to put parentheses defensively.


Thus we can conclude that objects and its methods provide the foundation on which object-oriented programming is based. The entire Ruby code is made up of only objects and method calls. Ruby being a pure object oriented language (everything is an object and every operation is a method call), has methods inherent to its nature. Ruby methods provide a way to organize code and promote re-use while defining the behavior of ruby objects belonging to a specific type.


  2. Section 6, 6.1, 13, 13.3

Further Reading


Personal tools