CSC/ECE 517 Fall 2012/ch1b 1w55 ms: Difference between revisions

From Expertiza_Wiki
Jump to navigation Jump to search
No edit summary
No edit summary
Line 11: Line 11:
===Everything is an Object===
===Everything is an Object===
Just about everything in Ruby, from numbers and strings to arrays is an object.
Just about everything in Ruby, from numbers and strings to arrays is an object.
In Ruby, we can ask any object, which all methods it responds to.  
In Ruby, we can ask any object, which all methods it responds to.
 
Examples:
Examples:


   1.It considers even an integer as an object.
   It considers even an integer as an object.
     57.methods
     57.methods
     It returns the entire list of methods that the “object” 57 responds to.
     It returns the entire list of methods that the “object” 57 responds to.


   2.Ruby considers “nil” as an object too.
   Ruby considers “nil” as an object too.
     nil.respond_to?(:to_s)
     nil.respond_to?(:to_s)
     It returns ‘true’ or ‘false’ depending on whether ‘nil’ responds to the method ‘to_s’.
     It returns ‘true’ or ‘false’ depending on whether ‘nil’ responds to the method ‘to_s’.
Line 89: Line 90:


   y = y + [“foo”, :bar]
   y = y + [“foo”, :bar]
 
  This will create a new object which is a concatenation of ‘y’ and the [“foo”, :bar] array.
The above example will create a new object which is a concatenation of ‘y’ and the [“foo”, :bar] array.
However,  
However, y << [6,7] will destructively modify the receiver ‘y’ and ‘y’ will become the new array [6,7].
  y << [6,7]  
  will destructively modify the receiver ‘y’ and ‘y’ will become the new array [6,7].


===Poetry Mode===
===Poetry Mode===

Revision as of 21:16, 3 October 2012

SaaS - 3.2, 3.3 - Ruby Objects and Methods

Introduction

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 divide the world between objects and primitive types. The hybrid approach yields better performance, but the pure object-oriented approach is more consistent 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 as the building blocks for a software application.

Objects consist of data variables and functions (called methods) that can be accessed and called on the object to perform 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, which all methods it responds to.

Examples:

  It considers even an integer as an object.
    57.methods
    It returns the entire list of methods that the “object” 57 responds to.
  Ruby considers “nil” as an object too.
    nil.respond_to?(:to_s)
    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 the influence of the Smalltalk language by giving methods and instance variables to all of its types. This eases one’s use of Ruby, since 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 their function will be. 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 ()
   end
   def test_method
      puts "The class is working"
   end
 end

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 = Student.new()

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

  student.test_method
  The class is working

Methods

What is a Method?

In Object-Oriented Programming, we do not operate on the data directly from outside the object; rather the objects have some understanding of how to operate on themselves. We pass messages to an object, and those messages will generally elicit some kind of an action or meaningful reply. 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:

  “abcdef”.length
  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:

  “abcdef”.send(:length)

‘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’.

Destructive Methods

Ruby methods that modify 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). 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, you get a new object. If you call the destructive version (with ‘!’), you operate in-place on the same object to which you sent the message. Example:

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

However,

  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. 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.

Conclusion

Thus we can conclude that objects and its methods provide the foundation on which object-oriented programming is based. 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.

References

  1. http://www.youtube.com/watch?v=iWhGWPOpkbU
  2. http://www.ipa.go.jp/osc/english/ruby/Ruby_final_draft_enu_20100825.pdf
  3. http://en.wikibooks.org/wiki/Ruby_Programming/Introduction_to_objects
  4. http://en.wikibooks.org/wiki/Ruby_Programming/Syntax/Method_Calls#Methods
  5. http://www.rubyist.net/~slagell/ruby/methods.html
  6. http://www.techotopia.com/index.php/Ruby_Object_Oriented_Programming#What_is_an_Object.3F
  7. http://www.techotopia.com/index.php/Ruby_Methods
  8. http://rubylearning.com/satishtalim/tutorial.html
  9. http://ruby-doc.org/docs/ProgrammingRuby/

Further Reading

  1. http://rubymonk.com/
  2. http://www.ruby-lang.org/en/documentation/quickstart
  3. http://www.ruby-doc.org/downloads/
  4. http://pragprog.com/titles/ruby3/programming-ruby-1-9
  5. http://oreilly.com/catalog/9780596516178/