CSC/ECE 517 Fall 2012/ch1b 1w55 ms: Difference between revisions
(3 intermediate revisions by the same user not shown) | |||
Line 34: | Line 34: | ||
====Defining a Ruby 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. | For defining Classes, we use the [http://en.wikipedia.org/wiki/Keyword_%28computer_programming%29 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: | We can illustrate this using an example: | ||
Line 55: | Line 55: | ||
student.test_method | student.test_method | ||
The class is working | The class is working | ||
Another Example: | |||
class Person | |||
attr_reader :name, :age | |||
def initialize(name, age) | |||
@name, @age = name, age | |||
end | |||
end | |||
# create 3 objects of class Person | |||
p1 = Person.new("Bob", 33), | |||
p2 = Person.new("Chris", 16), | |||
p3 = Person.new("Ash", 23) | |||
==Methods== | ==Methods== | ||
Line 87: | Line 101: | ||
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. | 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 | 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. | 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. | ||
Line 99: | Line 113: | ||
===Poetry Mode=== | ===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. | The parentheses in method calls and hashes are always optional, not just for zero-[http://en.wikipedia.org/wiki/Parameter_%28computer_programming%29#Parameters_and_arguments 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: | Example: | ||
Latest revision as of 01:25, 11 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 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.
Example:
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 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 () 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
Another Example:
class Person attr_reader :name, :age def initialize(name, age) @name, @age = name, age end end # create 3 objects of class Person p1 = Person.new("Bob", 33), p2 = Person.new("Chris", 16), p3 = Person.new("Ash", 23)
Methods
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:
“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’.
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.
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. 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.
Conclusion
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.
References
- http://www.youtube.com/watch?v=iWhGWPOpkbU
- http://www.ipa.go.jp/osc/english/ruby/Ruby_final_draft_enu_20100825.pdf Section 6, 6.1, 13, 13.3
- http://en.wikibooks.org/wiki/Ruby_Programming/Introduction_to_objects
- http://en.wikibooks.org/wiki/Ruby_Programming/Syntax/Method_Calls#Methods
- http://www.rubyist.net/~slagell/ruby/methods.html
- http://www.techotopia.com/index.php/Ruby_Object_Oriented_Programming#What_is_an_Object.3F
- http://www.techotopia.com/index.php/Ruby_Methods
- http://rubylearning.com/satishtalim/tutorial.html
- http://ruby.activeventure.com/programmingruby/book/tut_classes.html
- http://ruby-doc.org/docs/ProgrammingRuby/
- http://strugglingwithruby.blogspot.com/2008/12/ruby-classes.html
- http://strugglingwithruby.blogspot.com/2009/01/ruby-methods-part-4-calling-methods.html
- http://ruby.activeventure.com/programmingruby/book/tut_methods.html
- http://www.zenspider.com/Languages/Ruby/QuickRef.html
Further Reading
- http://rubymonk.com/
- http://www.ruby-lang.org/en/documentation/quickstart
- http://www.ruby-doc.org/downloads/
- http://pragprog.com/titles/ruby3/programming-ruby-1-9
- http://oreilly.com/catalog/9780596516178/
- http://eli.thegreenplace.net/2006/04/18/understanding-ruby-blocks-procs-and-methods/
- http://strugglingwithruby.blogspot.com/2008/12/ruby-methods-part-1-basics.html
- http://ruby.activeventure.com/programmingruby/book/index.html
- http://www.mentby.com/david-a-black/are-methods-objects.html