CSC/ECE 517 Fall 2011/ch3 4b js: Difference between revisions

From Expertiza_Wiki
Jump to navigation Jump to search
 
(100 intermediate revisions by 2 users not shown)
Line 1: Line 1:
=Lecture 5=
This wiki covers review topics from lecture 4 i.e. Closures and Currying followed by OOP in Ruby.
__TOC__
== Closures ==
== Closures ==
===What is a Closure?===
===What is a Closure?===
A closure is a block of code that can access the lexical environment of its definition.  A closure has two properties:  
 
A [http://en.wikipedia.org/wiki/Closure_(computer_science) closure] is a block of code that can access the lexical environment of its definition.  A closure has two properties:  
*A closure can be passed as an object.
*A closure can be passed as an object.
*A closure recalls the values of all the variables that were in scope when the function was created and is able to access those variables when it is called even though they may no longer be in scope.
*A closure recalls the values of all the variables that were in scope when the function was created and is able to access those variables when it is called even though they may no longer be in scope.
Line 9: Line 13:
Ruby supports closures through use of Procedures, or simply procs, and lambdas, which are blocks.  
Ruby supports closures through use of Procedures, or simply procs, and lambdas, which are blocks.  
====Blocks====  
====Blocks====  
In Ruby, blocks are used to group statements usually enclosed by braces or between a <b>do...end</b> and occur solely in the source adjacent to a method call.  Rule of thumb in Ruby is to use braces for blocks containing only a single line and <b>do...end</b> for multi-line blocks.  The code within the block is not executed when encountered, instead, Ruby recalls the context of the block and then enters the method.  Typically, the blocks passed into methods are anonymous objects that are created instantly, but they can be instantiated as a Proc object by using either the <b> proc </b> or <b> lambda </b> method.  Proc objects are blocks of code that have been bound to a set of local variables. Once bound, the code may be called in different contexts and still access those variables.[http://blog.mostof.it/why-ruby-part-two-blocks-and-closures/ (7)] Proc objects can be simply thought of as anonymous function objects.  Proc objects can be stored, created at runtime, passed as arguments, retrieved, as well as, be returned as values.  Consider the example below from [http://www.csc.ncsu.edu/faculty/efg/517/f11/lectures#j10 lecture 5]:
In Ruby, blocks are used to group statements usually enclosed by braces or between a <b>do...end</b> and occur solely in the source adjacent to a method call.  Rule of thumb in Ruby is to use braces for blocks containing only a single line and <b>do...end</b> for multi-line blocks.  The code within the block is not executed when encountered, instead, Ruby recalls the context of the block and then enters the method.  Typically, the blocks passed into methods are anonymous objects that are created instantly, but they can be instantiated as a Proc object by using either the <b> proc </b> or <b> lambda </b> method.  Proc objects are blocks of code that have been bound to a set of local variables. Once bound, the code may be called in different contexts and still access those variables.<ref>http://blog.mostof.it/why-ruby-part-two-blocks-and-closures/</ref> Proc objects can be simply thought of as anonymous function objects.  Proc objects can be stored, created at runtime, passed as arguments, retrieved, as well as, be returned as values.  Consider the example below from lecture 5 <ref> http://www.csc.ncsu.edu/faculty/efg/517/f11/lectures#j10</ref>:


Class to generate adders:
Class to generate adders:
Line 38: Line 42:


====Procs and Lambdas====
====Procs and Lambdas====
When creating a <b>lambda</b> or <b>proc</b>, the object holds a reference to the executable block and bindings for all the variables used by the block.  In Ruby, we can create a Proc object explicitly in three different ways:
When creating a <b>lambda</b> or <b>proc</b>, the object holds a reference to the executable block and bindings for all the variables used by the block. Procs in Ruby are first-class objects, because they can be created during runtime, stored in data structures, passed as arguments to other functions and returned as the value of other functions.  In Ruby, we can create a Proc object explicitly in three different ways:


====Proc.new====
=====Proc.new=====
Using this method involves simply passing in a block, which will return a Proc object that will run the code in the block when you invoke its call method.
Using this method involves simply passing in a block, which will return a Proc object that will run the code in the block when you invoke its call method.  The use of uppercase is to denote that <b>Proc</b> is a proper class within Ruby.
<pre>
<pre>
pobject = Proc.new {puts “This is a proc object.”}
pobject = Proc.new {puts “This is a proc object.”}
pobject.call  
pobject.call  
</pre>
</pre>
====proc method====   
 
In the Kernel module, we can use the proc method, which is available globally.  In Ruby 1.9, it is equivalent to Proc.new, but in Ruby 1.8, it is equivalent to lambda.  The difference between proc and lambda will be discussed later.  
=====proc method=====   
In the Kernel module, we can use the proc method, which is available globally.  In Ruby 1.9, it is equivalent to Proc.new, but in Ruby 1.8, it is equivalent to lambda.  The difference between proc and lambda will be discussed later.   Using the proc method comes in handy when we may have various blocks that are being used multiple times and passing the same block repeatedly would necessitate repeating ourself.  Using the proc method, you are saving the reusable code as an object itself, where the difference between a block and Proc is that a block cannot be saved and is a single use solution.
 
 
<pre>
<pre>
pobject = proc { puts “Inside the proc object” }
pobject = proc { puts “Inside the proc object” }
pobject.call  
pobject.call  
</pre>
</pre>
====lambda method====
 
Similar to the proc method, it is globally available in the Kernel module, however, it will create a lambda Proc object.
=====lambda method=====
Similar to the proc method, it is globally available in the Kernel module, however, it will create a lambda Proc object. The lambda proc objects are very similar to proc objects, though, the differences between lambdas and proc objects will be discussed in the next section.
 
<pre>
<pre>
pobject = lambda { puts “Inside the proc object” }
pobject = lambda { puts “Inside the proc object” }
pobject.call  
pobject.call
</pre>
</pre>


=== procs vs. lambdas ===
===== procs vs. lambdas =====
One difference between the proc kernel method and the lambda kernel method is that the lambda kernel method re
One difference between the proc kernel method and the lambda kernel method is that the lambda kernel method results in an object that checks the number of its arguments, while a plain Proc.new does not.  With Proc methods, extra variables are set to <b>nil</b>, whereas, with lambdas, Ruby throws an error instead.  Another difference between <b>procs</b> and <b>lambdas</b> is their handling of control flow keywords, such as <b>break</b> and <b>return</b>.  With a Proc <b>return</b>, it will stop a method and return the provided value, however, lambdas will return its value to the method and allow the method to continue on.  Consider the examples below <ref>http://www.skorks.com/2010/05/ruby-procs-and-lambdas-and-the-difference-between-them</ref> For instance, the first example below shows the difference in behavior using the <b>return</b> keyword.  With the proc method, the <b>return</b> not only returns from the proc method, but also the enclosing method, which is shown when the last <b>puts</b> is not called.
\\esults in an object that checks the number of its arguments, while a plain Proc.new does not:
 
Another difference between <b>procs</b> and <b>lambdas</b> is their handling of control flow keywords, such as <b>break</b> and <b>return</b>.  Consider the examples below [http://www.skorks.com/2010/05/ruby-procs-and-lambdas-and-the-difference-between-them (1)].  For instance, the first example below shows the difference in behavior using the <b>return</b> keyword.  With the proc method, the <b>return</b> not only returns from the proc method, but also the enclosing method, which is shown when the last <b>puts</b> is not called.
<pre>
<pre>
def my_method
def my_method
Line 82: Line 90:
inside proc
inside proc
</pre>
</pre>
If we exchange the proc for the lambda method, the <b>return </b> only returns from the lambda method and NOT the enclosing method, thus, it continues on to execute the last <b> puts </b>.
If we exchange the proc for the lambda method, the <b>return</b> only returns from the lambda method and NOT the enclosing method, thus, it continues on to execute the last <b>puts</b>.
<pre>
<pre>
def my_method
def my_method
Line 104: Line 112:
</pre>
</pre>


If we go back to the proc method, and use the <b> break </b> keyword in lieu of <b> return </b>.  However, instead of returning from the proc method and the enclosing method, we are issued a <i> LocalJumpError </i>.  Since <b> break</b> keywords are usually used to fall out of  an iteration, but it is not contained within an iteration, Ruby throws an error.
If we go back to the proc method, and use the <b>break</b> keyword in lieu of <b>return</b>, we see that instead of returning from the proc method and the enclosing method, we are issued a <i>LocalJumpError</i>.  Since <b>break</b> keywords are usually used to fall out of  an iteration, but it is not contained within an iteration, Ruby throws an error.


<pre>
<pre>
Line 130: Line 138:
</pre>
</pre>


Let us revisit the lambda method, but this time, we will use the <b> break </b> keyword.  You will notice that the <b> break </b> is treated like the <b> return </b> keyword, where the execution is dumped out of the lambda, but continues to execute the rest of the enclosing method.  
Let us revisit the lambda method, but this time, we will use the <b>break</b> keyword.  You will notice that the <b>break</b> is treated like the <b>return</b> keyword, where the execution is dumped out of the lambda, but continues to execute the rest of the enclosing method.  
<pre>
<pre>
def my_method
def my_method
Line 158: Line 166:
==Currying ==
==Currying ==


[http://www.khelll.com/blog/ruby/ruby-currying/ Currying] is a concept in Functional Programming that’s enabled by Higher-order functions. It is the technique of transforming a function that takes multiple arguments (or an n-tuple of arguments) in such a way that it can be called as a chain of functions each with a single argument (partial application).
[http://en.wikipedia.org/wiki/Currying Currying] is a concept in Functional Programming that’s enabled by Higher-order functions. It is the technique of transforming a function that takes multiple arguments (or an n-tuple of arguments) in such a way that it can be called as a chain of functions each with a single argument (partial application) <ref>http://www.khelll.com/blog/ruby/ruby-currying/</ref>
Given a function f of type <pre>f:(X x Y)-->Z</pre>  
Given a function f of type <pre>f:(X x Y)-->Z</pre>  
Currying it makes a function <pre>curry(f): X-->(Y-->Z)</pre>
Currying it makes a function <pre>curry(f): X-->(Y-->Z)</pre>
Line 221: Line 229:
==Object-Oriented Programming in Ruby ==
==Object-Oriented Programming in Ruby ==
Ruby is the ideal Object Oriented Programming Language, which has four essential properties:
Ruby is the ideal Object Oriented Programming Language, which has four essential properties:
*Data Encapsulation
[[File:Ruby.jpg| right| Ruby ]]
*Data Abstraction
*[http://en.wikipedia.org/wiki/Encapsulation_(object-oriented_programming) Data Encapsulation]
*Polymorphism
*[http://en.wikipedia.org/wiki/Abstraction_(computer_science) Data Abstraction]
*Inheritance
*[http://en.wikipedia.org/wiki/Polymorphism_in_object-oriented_programming Polymorphism]
*[http://en.wikipedia.org/wiki/Inheritance_(object-oriented_programming) Inheritance]


An object-oriented program consists of classes and objects.  An object consists of state and related behavior, where its state is contained within fields and allows access to its behavior through use of methods. These methods can alter an object's state and serve as the facilitator for communication between objects.  Classes are defined as the building blocks from which objects are created and will be explained further as we progress through the four properties through the subsequent sections.
An object-oriented program consists of [http://en.wikipedia.org/wiki/Class_(computer_programming) classes] and [http://en.wikipedia.org/wiki/Object_(object-oriented_programming) objects].  An object consists of state and related behavior, where its state is contained within fields and allows access to its behavior through use of methods. These methods can alter an object's state and serve as the facilitator for communication between objects.  Classes are defined as the building blocks from which objects are created and will be explained further as we progress through the four properties through the subsequent sections.


===Classes ===
===Classes ===
Line 262: Line 271:
</pre>
</pre>


The <b> attr_accessor </b> method dynamically defines the read and write methods for the two instance variables.  Using the keyword <b> self </b> is a way to refer to the current object, which is the receiver that invokes all method calls in Ruby.  To instantiate an object of the new class, we use <b> <varname> = <classname>.new(arg1,arg2)</b>, which automatically calls the <b> initialize </b> method of the class and passes the arguments to the <b> initialize </b> method.  Using our <b> Person </b> class defined above, we can instantiate objects as follows:
The <b> attr_accessor </b> method dynamically defines the read and write methods for the two instance variables.  To instantiate an object of the new class, we use <b> <varname> = <classname>.new(arg1,arg2)</b>, which automatically calls the <b> initialize </b> method of the class and passes the arguments to the <b> initialize </b> method.  Using our <b> Person </b> class defined above, we can instantiate objects as follows:
<pre>
<pre>
pers1 = Person.new("John","Smith")
pers1 = Person.new("John","Smith")
Line 268: Line 277:
</pre>
</pre>


====Methods ====
====Instance Methods====
Since our class has instance variables and class variables, our state, it's only natural that there would be instance methods and class methods, our behavior. 
=====Instance Methods=====
Ruby methods are defined using the keyword <b> def </b>, where the signature is the method name.    The <b> to_s </b> method returns a String representation of the object, so for the <b> Person </b>, it returns a string concatenation of the first and last name.  Since the <b> to_s </b> method in the <b> Person </b> class is already defined in Object, and we have redefined it in our <b> Person </b> class, Ruby will use the last implementation of the method.  Since Ruby returns the value of the last expression of a method as the return value, we can in fact invoke the <b> to_s </b> method in two ways:
Ruby methods are defined using the keyword <b> def </b>, where the signature is the method name.    The <b> to_s </b> method returns a String representation of the object, so for the <b> Person </b>, it returns a string concatenation of the first and last name.  Since the <b> to_s </b> method in the <b> Person </b> class is already defined in Object, and we have redefined it in our <b> Person </b> class, Ruby will use the last implementation of the method.  Since Ruby returns the value of the last expression of a method as the return value, we can in fact invoke the <b> to_s </b> method in two ways:


Line 282: Line 289:
</pre>
</pre>


=====Class Methods====
====Class Methods====
TBD
In Ruby, class methods actually belong to the class and not the instantiation of an object, such as above.  In our <b> Person </b> class above, the method <b> self.info </b> is actually a class method, which prints the number of instances of the <b> Person </b> class.  A class method is defined by prefixing the method name with the keyword <b> self </b>.  When inside an instance method, <b> self </b> is the receiver object, whereas, outside of an instance method, but within a class definition, self, in fact, refers to the class.  To invoke a class method, you must call the class method by prefixing it with the class name, where it will resolve to the class.
 
<pre>
# Print number of instances.
puts Person.info
</pre>


===Attributes===
===Attributes===


Usually methods are defined to give access and power to change the state of an object. If the objects created have a private state, it means no other object can access its instance variables. In other words, object itself is responsible for maintaining its own consistency, however it’s not of much use since you can’t do anything with it. One wants to create methods so that outside world can interact with it. These external visible aspects of an object are called its attributes.
Usually methods are defined to give access and power to change the state of an object. If the objects created have a private state, it means no other object can access its instance variables. In other words, object itself is responsible for maintaining its own consistency, however it’s not of much use since you can’t do anything with it. One wants to create methods so that outside world can interact with it. These external visible aspects of an object are called its attributes <ref>http://ruby-doc.org/docs/ProgrammingRuby/html/tut_classes.html</ref>


Ruby provides some convenient method to define accessor methods: attr_accessor, attr_writer and attr_reader. Attributes are just a shortcut. If you use attr_accessor to create an attribute, Ruby just declares an instance variable and creates getter and setter methods.
Ruby provides convenient methods to define accessor methods: attr_accessor, attr_writer and attr_reader. Attributes are just a shortcut i.e. if you use attr_accessor to create an attribute, Ruby just declares an instance variable and creates getter and setter methods.


<pre>
<pre>
Line 352: Line 364:
====Attributes, Instance Variables, and Methods====
====Attributes, Instance Variables, and Methods====


An attribute can act as a method. It can return the value of an instance variable or result of a calculation and sometimes these methods with equals signs at the end of their names are used to update the state of an object.  
An attribute can act as a method. It can return the value of an instance variable or result of a calculation and sometimes these methods with equals signs at the end of their names are used to update the state of an object <ref>http://books.google.com/books/about/Programming_Ruby.html?id=-YVQAAAAMAAJ</ref>


To differentiate an attribute with method, Dave Thomas, author of the book, Programming ruby, The pragmatic programmers guide, quotes “When you design a class, you decide what internal state it has and also decide how that state is to appear on the outside (to users of your class). The internal state is held in instance variables. The external state is exposed through methods we’re calling attributes. And the other actions your class can perform are just regular methods. It really isn’t a crucially important distinction, but by calling the external state of an object its attributes, you’re helping clue people in to how they should view the class you’ve written.”
To differentiate an attribute from the method, Dave Thomas, author of the book, Programming ruby, The pragmatic programmers guide, quotes “When you design a class, you decide what internal state it has and also decide how that state is to appear on the outside (to users of your class). The internal state is held in instance variables. The external state is exposed through methods we’re calling attributes. And the other actions your class can perform are just regular methods. It really isn’t a crucially important distinction, but by calling the external state of an object its attributes, you’re helping clue people in to how they should view the class you’ve written.”


===Inheritance===
===Inheritance===
<b> Inheritance </b> is one of the basic principles of Object-Oriented programming, where Inheritance is a method of altering or reusing code of existing objects.  The inherited class is called the super, or base, class, and the class that inherits from the base class is referred to as the subclass.  Simply, the base class is commonly the more generic form of the subclass.  In Ruby, inheritance is indicated by use of the <b><</b> operator.  Using our <b>Person</b> class from above, we will define an <b>Employee</b> class which will inherit from the <b>Person</b> class.
<pre>
class Employee < Person
  attr_accessor :salary
  def initialize(fname, lname, salary)
      super(fname, lname)
      @salary = salary
  end
  def to_s
      super + " Salary: #{@salary}"
  end
end
</pre>
In the subclass, <b>Employee</b>, we added an instance variable called <b>salary</b>.  Within the subclass's <b>initialize</b> method, the <b>initialize</b> method of the super class is called first using <b>super</b> and passing it the arguments <b>fname</b> and <b>lname</b>, then sets the <b>salary</b>.  By redefining the <b>to_s</b> method in the <b>Employee</b> class, we have overridden the <b>to_s</b> that was defined in the <b>Person</b> class.  The <b>super</b> within the <b>to_s</b> method calls the <b>to_s</b> of the superclass, the <b>Person</b>class, which returns a string.  So, the <b>to_s</b> method concatenates the string returned from calling the <b>to_s</b> from the superclass with the additional salary information.
===Access Control===
===Access Control===


Line 374: Line 404:
Access levels are specified to methods within class or module definitions using one or more of these three functions public, protected, and private. Each function can be used in two different ways.
Access levels are specified to methods within class or module definitions using one or more of these three functions public, protected, and private. Each function can be used in two different ways.


If no arguments are passed, the three functions set the default access control of subsequently defined methods.
If no arguments are passed, the three functions set the default access control of subsequently defined methods <ref>http://rubylearning.com/satishtalim/ruby_access_control.html</ref>
http://rubylearning.com/satishtalim/ruby_access_control.html


<pre>
<pre>
Line 410: Line 439:


Protected access is used when objects need to access the internal state of other objects of the same class.
Protected access is used when objects need to access the internal state of other objects of the same class.
====Public, Protected and Private Visibility====
Summing it up <ref>http://adhirajrankhambe.wordpress.com/2010/05/02/access-control-in-ruby/</ref>
=====Public Visibility=====
# The default access level is “Public”. Public methods are accessible from anywhere (within the class, outside the class, same instance, other instances of same class and sub-classes).
=====Protected Visibility=====
# Protected methods are visible to all the instances of the same class as well as sub-classes.
# Protected methods are also accessible from sub-classes. In short, Access control in Ruby neither applies to nor impacts the object hierarchy.
# While accessing protected methods, you can specify the receiver; receiver can by explicit or implicit.
# “Protected” in Ruby is not quite common in other programming languages.
# Private and Protected methods are not directly accessible outside the class.
=====Private Visibility=====
# Private methods are private to the instance (and not to the class).
# Private methods are accessible from sub-classes. 

# While accessing private methods, one cannot specify the receiver (even if its “self”), receiver is always implicit, never explicit.
# “Private” in Ruby is what “Protected” is in many other languages.
# In Ruby, no method is perfectly private or hidden.


===Abstract Methods===
===Abstract Methods===
An [http://en.wikipedia.org/wiki/Method_(computer_programming)#Abstract_methods <b>Abstract Method</b>] is a method that has a signature, but it does not have an implementation and are commonly used to specify intefaces.  Abstract methods force the subclass to provide the implementation of the method.  Let's add an abstract method called <b>fullname</b> to the <b>Person</b> class. In the <b>fullname</b>, we want to print the person's first, middle, and last name, however, the middle name variable <b>mname</b> is not defined in the <b>Person</b>, so it must be defined in the superclass to avoid an implementation error.
<pre>
class Person
  @@count = 0
  attr_accessor :fname, :lname.
  def initialize(fname,lname)
    @fname = fname
    @lname = lname
    @@count += 1
  end
  def self.info
      puts "Number of instances = #{@@count}"
  end
  def fullname
      "Name: #{@fname} #{@mname} #{@lname}"
  end
  def to_s
    "Name: #{@fname} #{@lname}"
  end
end
</pre>
In the subclass <b>Employee</b>, we have added the instance variable <b>mname</b> along with the read/write methods for <b>mname</b>. 
<pre>
class Employee < Person
  attr_accessor :salary
  attr_accessor :mname
  def initialize(fname, mname,lname, salary)
      super(fname, lname)
      @salary = salary
      @mname  = mname
  end
  def to_s
      super + " Salary: #{@salary}"
  end 
end
</pre>
Since, <b>mname</b> is now defined, when we call the method <b>fullname</b>, it prints the Employee's first, middle, and last name:
<pre>
Employee.new("Jimmy","James","Johnson",35000).fullname
>> Name: Jimmy James Johnson
</pre>


===Duck Typing (Unbounded Polymorphism)===
===Duck Typing (Unbounded Polymorphism)===
Relying less on the type (or class) of an object and more on its capabilities is called [http://en.wikipedia.org/wiki/Duck_typing duck typing]. If an object walks like a duck and talks like a duck, then the interpreter is happy to treat it as if it were a duck.
<pre>
duck << "quack"
</pre>
In the above example, duck can be a String, a File, or an Array (which is very useful when writing unit tests) <ref>http://blade.nagaokaut.ac.jp/cgi-bin/scat.rb/ruby/ruby-talk/78502</ref>
Duck typing is a style of dynamic typing in which an object's current set of methods and properties determines the valid semantics, rather than its inheritance from a particular class or implementation of a specific interface. In duck typing, one is concerned with just those aspects of an object that are used, rather than with the type of the object itself. There is no need for testing the type of arguments in method and function bodies <ref>http://en.wikipedia.org/wiki/Duck_typing</ref>
<pre>
class Duck
  def quack
    puts "Quaaaaaack!"
  end
  def feathers
    puts "The duck has feathers."
  end
end
class Person
  def quack
    puts "The person imitates a duck."
  end
  def feathers
    puts "Person has no feather"
  end
end
def test_method duck
  duck.quack
  duck.feathers
end
def game
  donald = Duck.new
  person = Person.new
  test_method donald
  test_method person
end
game
</pre>
Output of the above program:
<pre>
Quaaaaaack!
The duck has feathers.
The person imitates a duck.
Person has no feather.
</pre>
In a non-duck-typed language, one can create a function that takes an object of type Duck/Person and calls that object's walk and feathers methods. In a duck-typed language as shown above, the equivalent function would take an object of any type and call that object's walk and feathers methods. If the object does not have the methods that are called then the function signals a run-time error.


== References ==
== References ==
*[http://www.skorks.com/2010/05/ruby-procs-and-lambdas-and-the-difference-between-them (1)http://www.skorks.com/2010/05/ruby-procs-and-lambdas-and-the-difference-between-them]
<references />
*[http://samdanielson.com/2007/9/6/an-introduction-to-closures-in-ruby (2)http://samdanielson.com/2007/9/6/an-introduction-to-closures-in-ruby]
*[http://en.wikipedia.org/wiki/Closure_(computer_science) (3)http://en.wikipedia.org/wiki/Closure_(computer_science)]
*[http://en.wikipedia.org/wiki/Continuation-passing_style (4)http://en.wikipedia.org/wiki/Continuation-passing_style]
*[http://www.amazon.com/Ruby-Programming-Language-David-Flanagan/dp/0596516177/ref=sr_1_1?ie=UTF8&qid=1318716890&sr=8-1 (5)Flanagan, D and Matsumoto, Y, (2008). The Ruby Programming Language, O’Reilly Media, Inc.,]
*[http://www.amazon.com/Learning-Ruby-Michael-James-Fitzgerald/dp/0596529864/ref=sr_1_1?s=books&ie=UTF8&qid=1318716919&sr=1-1 (6)Fitzgerald Michael, (2007). Learning Ruby, O’Reilly Media, Inc., (example)]
*[http://blog.mostof.it/why-ruby-part-two-blocks-and-closures/ (7)http://blog.mostof.it/why-ruby-part-two-blocks-and-closures/]

Latest revision as of 16:53, 30 October 2011

Lecture 5

This wiki covers review topics from lecture 4 i.e. Closures and Currying followed by OOP in Ruby.

Closures

What is a Closure?

A closure is a block of code that can access the lexical environment of its definition. A closure has two properties:

  • A closure can be passed as an object.
  • A closure recalls the values of all the variables that were in scope when the function was created and is able to access those variables when it is called even though they may no longer be in scope.

A closure can be expressed succintly as a function pointer that references a block of executable code and the variables from the scope it was created.

Closures in Ruby

Ruby supports closures through use of Procedures, or simply procs, and lambdas, which are blocks.

Blocks

In Ruby, blocks are used to group statements usually enclosed by braces or between a do...end and occur solely in the source adjacent to a method call. Rule of thumb in Ruby is to use braces for blocks containing only a single line and do...end for multi-line blocks. The code within the block is not executed when encountered, instead, Ruby recalls the context of the block and then enters the method. Typically, the blocks passed into methods are anonymous objects that are created instantly, but they can be instantiated as a Proc object by using either the proc or lambda method. Proc objects are blocks of code that have been bound to a set of local variables. Once bound, the code may be called in different contexts and still access those variables.<ref>http://blog.mostof.it/why-ruby-part-two-blocks-and-closures/</ref> Proc objects can be simply thought of as anonymous function objects. Proc objects can be stored, created at runtime, passed as arguments, retrieved, as well as, be returned as values. Consider the example below from lecture 5 <ref> http://www.csc.ncsu.edu/faculty/efg/517/f11/lectures#j10</ref>:

Class to generate adders:


class AdderGen
   def initialize(n)
      @block = lambda {|a| n + a }
   end

   def add(a)
      @block.call a
   end
end

twoAdder    = AdderGen.new 2
incrementer = AdderGen.new 1

puts incrementer.add(4)
puts twoAdder.add(6)
>> 5
>> 8

In the example above, the instance variable @block is a closure and it recalls the parameter from which the initialize method was called after the initialize method exits and it is used when the block is called in the add method. This example also uses the lambda method to generate new functions dynamically, which will be discussed in the next section.

Procs and Lambdas

When creating a lambda or proc, the object holds a reference to the executable block and bindings for all the variables used by the block. Procs in Ruby are first-class objects, because they can be created during runtime, stored in data structures, passed as arguments to other functions and returned as the value of other functions. In Ruby, we can create a Proc object explicitly in three different ways:

Proc.new

Using this method involves simply passing in a block, which will return a Proc object that will run the code in the block when you invoke its call method. The use of uppercase is to denote that Proc is a proper class within Ruby.

pobject = Proc.new {puts “This is a proc object.”}
pobject.call 
proc method

In the Kernel module, we can use the proc method, which is available globally. In Ruby 1.9, it is equivalent to Proc.new, but in Ruby 1.8, it is equivalent to lambda. The difference between proc and lambda will be discussed later. Using the proc method comes in handy when we may have various blocks that are being used multiple times and passing the same block repeatedly would necessitate repeating ourself. Using the proc method, you are saving the reusable code as an object itself, where the difference between a block and Proc is that a block cannot be saved and is a single use solution.


pobject = proc { puts “Inside the proc object” }
pobject.call 
lambda method

Similar to the proc method, it is globally available in the Kernel module, however, it will create a lambda Proc object. The lambda proc objects are very similar to proc objects, though, the differences between lambdas and proc objects will be discussed in the next section.

pobject = lambda { puts “Inside the proc object” }
pobject.call
procs vs. lambdas

One difference between the proc kernel method and the lambda kernel method is that the lambda kernel method results in an object that checks the number of its arguments, while a plain Proc.new does not. With Proc methods, extra variables are set to nil, whereas, with lambdas, Ruby throws an error instead. Another difference between procs and lambdas is their handling of control flow keywords, such as break and return. With a Proc return, it will stop a method and return the provided value, however, lambdas will return its value to the method and allow the method to continue on. Consider the examples below <ref>http://www.skorks.com/2010/05/ruby-procs-and-lambdas-and-the-difference-between-them</ref> For instance, the first example below shows the difference in behavior using the return keyword. With the proc method, the return not only returns from the proc method, but also the enclosing method, which is shown when the last puts is not called.

def my_method
  puts "before proc"
  my_proc = Proc.new do
    puts "inside proc"
    return
  end
  my_proc.call
  puts "after proc"
end
 
my_method
user@user-ubuntu:/home/user/ruby$ ruby a.rb
before proc
inside proc

If we exchange the proc for the lambda method, the return only returns from the lambda method and NOT the enclosing method, thus, it continues on to execute the last puts.

def my_method
  puts "before proc"
  my_proc = lambda do
    puts "inside proc"
    return
  end
  my_proc.call
  puts "after proc"
end
 
my_method
user@user-ubuntu:/home/user/ruby$ ruby a.rb
before proc
inside proc
after proc

If we go back to the proc method, and use the break keyword in lieu of return, we see that instead of returning from the proc method and the enclosing method, we are issued a LocalJumpError. Since break keywords are usually used to fall out of an iteration, but it is not contained within an iteration, Ruby throws an error.

def my_method
  puts "before proc"
  my_proc = Proc.new do
    puts "inside proc"
    break
  end
  my_proc.call
  puts "after proc"
end
 
my_method
user@user-ubuntu:/home/user/ruby$ ruby a.rb
before proc
inside proc
a.rb:64:in `block in my_method': break from proc-closure (LocalJumpError)
    from a.rb:66:in `call'
    from a.rb:66:in `my_method'
    from a.rb:70:in `<main>'

Let us revisit the lambda method, but this time, we will use the break keyword. You will notice that the break is treated like the return keyword, where the execution is dumped out of the lambda, but continues to execute the rest of the enclosing method.

def my_method
  puts "before proc"
  my_proc = lambda do
    puts "inside proc"
    break
  end
  my_proc.call
  puts "after proc"
end
 
my_method
user@user-ubuntu:/home/user/ruby$ ruby a.rb
before proc
inside proc
after proc

Why use Closures?

Closures not only enable programmers to write logic with less code, they are also useful in iterating over lists and encapsulation operations that require setup and clean-up afterwards.

Currying

Currying is a concept in Functional Programming that’s enabled by Higher-order functions. It is the technique of transforming a function that takes multiple arguments (or an n-tuple of arguments) in such a way that it can be called as a chain of functions each with a single argument (partial application) <ref>http://www.khelll.com/blog/ruby/ruby-currying/</ref>

Given a function f of type

f:(X x Y)-->Z

Currying it makes a function

curry(f): X-->(Y-->Z)

That is curry(f) takes an argument of type X and

Returns a function of type

Y-->Z

The following method is to sum all integers, to sum the squares of all integers and to sum the powers 2^n of all integers n between two given numbers a and b.

// Normal definitions

sum_ints = lambda do |a,b|
  s = 0 ; a.upto(b){|n| s += n } ; s 
end

sum_of_squares = lambda do |a,b|
  s = 0 ; a.upto(b){|n| s += n**2 } ;s 
end
 
sum_of_powers_of_2 = lambda do |a,b|
  s = 0 ; a.upto(b){|n| s += 2**n } ; s 
end
 
puts sum_ints.(1,5) #=> 15
puts sum_of_squares.(1,5) #=> 55
puts sum_of_powers_of_2.(1,5) #=> 62

// After factoring out the common pattern by defining a method sum

# Some refactoring to make some abstraction
# Passing the sum mechanism itself

sum = lambda do |f,a,b|
  s = 0 ; a.upto(b){|n| s += f.(n) } ; s 
end
 
puts sum.(lambda{|x| x},1,5) #=> 15
puts sum.(lambda{|x| x**2},1,5) #=> 55
puts sum.(lambda{|x| 2**x},1,5) #=> 62

// Passing the first param to the sum method to specify what type of sum it is

# Refactoring using currying 
# generate the currying

currying = sum.curry
 
 Generate the partial functions
sum_ints = currying.(lambda{|x| x})
sum_of_squares = currying.(lambda{|x| x**2})
sum_of_powers_of_2 = currying.(lambda{|x| 2**x})
 
puts sum_ints.(1,5) #=> 15
puts sum_of_squares.(1,5) #=> 55
puts sum_of_powers_of_2.(1,5) #=> 62

Object-Oriented Programming in Ruby

Ruby is the ideal Object Oriented Programming Language, which has four essential properties:

Ruby
Ruby

An object-oriented program consists of classes and objects. An object consists of state and related behavior, where its state is contained within fields and allows access to its behavior through use of methods. These methods can alter an object's state and serve as the facilitator for communication between objects. Classes are defined as the building blocks from which objects are created and will be explained further as we progress through the four properties through the subsequent sections.

Classes

To learn more about classes, let us first define a basic Person class.

class Person
end

The keyword class is used to define a class type with the class name in camel case, and the keyword end denotes the end of the code block. The Person class defined above explicitly inherits from Object. As we stated before, a class usually has state and behavior, so we will add instance variables, fname and lname , as well as, the necessary accessor methods, getters and setters and a class variable count to keep track of the number of instances of the class created.

class Person

   @@count = 0

   attr_accessor :fname, :lname.

   def initialize(fname,lname)
     @fname = fname
     @lname = lname
     @@count += 1
   end

   def self.info
      puts "Number of instances = #{@@count}"
   end

   def to_s
     "Name: #{@fname} #{@lname}"
   end
end

The attr_accessor method dynamically defines the read and write methods for the two instance variables. To instantiate an object of the new class, we use <varname> = <classname>.new(arg1,arg2), which automatically calls the initialize method of the class and passes the arguments to the initialize method. Using our Person class defined above, we can instantiate objects as follows:

pers1 = Person.new("John","Smith")
pers2 = Person.new("Tammy","Lee")

Instance Methods

Ruby methods are defined using the keyword def , where the signature is the method name. The to_s method returns a String representation of the object, so for the Person , it returns a string concatenation of the first and last name. Since the to_s method in the Person class is already defined in Object, and we have redefined it in our Person class, Ruby will use the last implementation of the method. Since Ruby returns the value of the last expression of a method as the return value, we can in fact invoke the to_s method in two ways:

#Implicit call to_s
puts pers1

#Explicit call to_s
str_name = pers1.to_s
puts str_name

Class Methods

In Ruby, class methods actually belong to the class and not the instantiation of an object, such as above. In our Person class above, the method self.info is actually a class method, which prints the number of instances of the Person class. A class method is defined by prefixing the method name with the keyword self . When inside an instance method, self is the receiver object, whereas, outside of an instance method, but within a class definition, self, in fact, refers to the class. To invoke a class method, you must call the class method by prefixing it with the class name, where it will resolve to the class.

# Print number of instances.
puts Person.info

Attributes

Usually methods are defined to give access and power to change the state of an object. If the objects created have a private state, it means no other object can access its instance variables. In other words, object itself is responsible for maintaining its own consistency, however it’s not of much use since you can’t do anything with it. One wants to create methods so that outside world can interact with it. These external visible aspects of an object are called its attributes <ref>http://ruby-doc.org/docs/ProgrammingRuby/html/tut_classes.html</ref>

Ruby provides convenient methods to define accessor methods: attr_accessor, attr_writer and attr_reader. Attributes are just a shortcut i.e. if you use attr_accessor to create an attribute, Ruby just declares an instance variable and creates getter and setter methods.

class Thing
    attr_accessor :my_property
    attr_reader :my_readable_property
    attr_writer :my_writable_property

    def do_stuff
        # does stuff
    end
end

Writable Attributes

Sometimes you need to be able to set an attribute from outside the object. In Ruby, the attributes of an object can be accessed as if they were any other variable.

class Song
  def duration=(newDuration)
    @duration = newDuration
  end
end
aSong = Song.new("Bicylops", "Fleck", 260)
aSong.duration	»	260
aSong.duration = 257   # set attribute with updated value
aSong.duration	»	257

Ruby also provides a shortcut for creating these simple attribute-setting methods.

class Song
  attr_writer :duration
end
aSong = Song.new("Bicylops", "Fleck", 260)
aSong.duration = 257

Virtual Attributes

Attribute-accessing methods don’t just have to be simple wrappers around an object's instance variables. In the following example, attribute methods have been used to create a virtual instance variable. To the outside world, durationInMinutes seems to be an attribute like any other but internally; there is no corresponding instance variable.

class Song
  def durationInMinutes
    @duration/60.0   # force floating point
  end
  def durationInMinutes=(value)
    @duration = (value*60).to_i
  end
end
aSong = Song.new("Bicylops", "Fleck", 260)
aSong.durationInMinutes	»	4.333333333
aSong.durationInMinutes = 4.2
aSong.duration	»	252

Bertrand Meyer calls this as Uniform Access Principle in book Object-Oriented Software Construction. This way the implementation of the class is hidden from the world and is a big advantage.

Attributes, Instance Variables, and Methods

An attribute can act as a method. It can return the value of an instance variable or result of a calculation and sometimes these methods with equals signs at the end of their names are used to update the state of an object <ref>http://books.google.com/books/about/Programming_Ruby.html?id=-YVQAAAAMAAJ</ref>

To differentiate an attribute from the method, Dave Thomas, author of the book, Programming ruby, The pragmatic programmers guide, quotes “When you design a class, you decide what internal state it has and also decide how that state is to appear on the outside (to users of your class). The internal state is held in instance variables. The external state is exposed through methods we’re calling attributes. And the other actions your class can perform are just regular methods. It really isn’t a crucially important distinction, but by calling the external state of an object its attributes, you’re helping clue people in to how they should view the class you’ve written.”

Inheritance

Inheritance is one of the basic principles of Object-Oriented programming, where Inheritance is a method of altering or reusing code of existing objects. The inherited class is called the super, or base, class, and the class that inherits from the base class is referred to as the subclass. Simply, the base class is commonly the more generic form of the subclass. In Ruby, inheritance is indicated by use of the < operator. Using our Person class from above, we will define an Employee class which will inherit from the Person class.


class Employee < Person
   attr_accessor :salary
   def initialize(fname, lname, salary)
      super(fname, lname)
      @salary = salary
   end
   def to_s
      super + " Salary: #{@salary}"
   end
end

In the subclass, Employee, we added an instance variable called salary. Within the subclass's initialize method, the initialize method of the super class is called first using super and passing it the arguments fname and lname, then sets the salary. By redefining the to_s method in the Employee class, we have overridden the to_s that was defined in the Person class. The super within the to_s method calls the to_s of the superclass, the Personclass, which returns a string. So, the to_s method concatenates the string returned from calling the to_s from the superclass with the additional salary information.

Access Control

Allowing much access into class has a risk of increased coupling in the application. Users in this case tend to depend on the class's implementation, rather than on its logical interface. Since the only way to change the state of an object is through calling its methods. Hence, Ruby gives us three levels of protection.

• Public methods can be called by anyone and there is no access control. Methods are public by default (except for initialize, which is always private).

• Protected methods can be invoked only by objects of the defining class and its subclasses. Access is kept within the family.

• Private methods cannot be called with an explicit receiver. Since you cannot specify an object when using them, private methods can be called only in the defining class and by direct descendants within that same object.

If a method is protected, it may be called by any instance of the class or its subclasses. If a method is private, it may be called only within the context of the calling object. One can never access another objects private methods directly, even if the object is of the same class as the caller.

Ruby differs from other OO languages in terms of access control i.e. it is determined dynamically, as the program runs, not statically. One will get an access violation only when the code attempts to execute the restricted method.

Specifying Access Control

Access levels are specified to methods within class or module definitions using one or more of these three functions public, protected, and private. Each function can be used in two different ways.

If no arguments are passed, the three functions set the default access control of subsequently defined methods <ref>http://rubylearning.com/satishtalim/ruby_access_control.html</ref>

class ClassAccess  
  def m1          # this method is public  
  end  
  protected  
    def m2        # this method is protected  
    end  
  private  
    def m3        # this method is private  
    end  
end  
ca = ClassAccess.new  
ca.m1  
#ca.m2  
#ca.m3  

Removing the comments from the last two statements in the above program, will give an access violation runtime error. Alternatively, one can set access levels of named methods by listing them as arguments to the access control functions.

class ClassAccess  
  def m1       # this method is public  
  end  
  public :m1  
  protected :m2, :m3  
  private :m4, :m5  
end  

A class's initialize method is automatically declared to be private.

Protected access is used when objects need to access the internal state of other objects of the same class.

Public, Protected and Private Visibility

Summing it up <ref>http://adhirajrankhambe.wordpress.com/2010/05/02/access-control-in-ruby/</ref>

Public Visibility
  1. The default access level is “Public”. Public methods are accessible from anywhere (within the class, outside the class, same instance, other instances of same class and sub-classes).
Protected Visibility
  1. Protected methods are visible to all the instances of the same class as well as sub-classes.
  2. Protected methods are also accessible from sub-classes. In short, Access control in Ruby neither applies to nor impacts the object hierarchy.
  3. While accessing protected methods, you can specify the receiver; receiver can by explicit or implicit.
  4. “Protected” in Ruby is not quite common in other programming languages.
  5. Private and Protected methods are not directly accessible outside the class.
Private Visibility
  1. Private methods are private to the instance (and not to the class).
  2. Private methods are accessible from sub-classes. 

  3. While accessing private methods, one cannot specify the receiver (even if its “self”), receiver is always implicit, never explicit.
  4. “Private” in Ruby is what “Protected” is in many other languages.
  5. In Ruby, no method is perfectly private or hidden.

Abstract Methods

An Abstract Method is a method that has a signature, but it does not have an implementation and are commonly used to specify intefaces. Abstract methods force the subclass to provide the implementation of the method. Let's add an abstract method called fullname to the Person class. In the fullname, we want to print the person's first, middle, and last name, however, the middle name variable mname is not defined in the Person, so it must be defined in the superclass to avoid an implementation error.

class Person
   @@count = 0

   attr_accessor :fname, :lname.

   def initialize(fname,lname)
     @fname = fname
     @lname = lname
     @@count += 1
   end

   def self.info
      puts "Number of instances = #{@@count}"
   end

   def fullname
      "Name: #{@fname} #{@mname} #{@lname}"
   end

   def to_s
     "Name: #{@fname} #{@lname}"
   end
end

In the subclass Employee, we have added the instance variable mname along with the read/write methods for mname.

class Employee < Person
   attr_accessor :salary
   attr_accessor :mname

   def initialize(fname, mname,lname, salary)
      super(fname, lname)
      @salary = salary
      @mname  = mname
   end
   def to_s
      super + " Salary: #{@salary}"
   end   
end

Since, mname is now defined, when we call the method fullname, it prints the Employee's first, middle, and last name:

Employee.new("Jimmy","James","Johnson",35000).fullname

>> Name: Jimmy James Johnson

Duck Typing (Unbounded Polymorphism)

Relying less on the type (or class) of an object and more on its capabilities is called duck typing. If an object walks like a duck and talks like a duck, then the interpreter is happy to treat it as if it were a duck.

 duck << "quack" 

In the above example, duck can be a String, a File, or an Array (which is very useful when writing unit tests) <ref>http://blade.nagaokaut.ac.jp/cgi-bin/scat.rb/ruby/ruby-talk/78502</ref> Duck typing is a style of dynamic typing in which an object's current set of methods and properties determines the valid semantics, rather than its inheritance from a particular class or implementation of a specific interface. In duck typing, one is concerned with just those aspects of an object that are used, rather than with the type of the object itself. There is no need for testing the type of arguments in method and function bodies <ref>http://en.wikipedia.org/wiki/Duck_typing</ref>

class Duck
  def quack
    puts "Quaaaaaack!"
  end
 
  def feathers
    puts "The duck has feathers."
  end
end
 
class Person
  def quack
    puts "The person imitates a duck."
  end
 
  def feathers
    puts "Person has no feather"
  end
end
 
def test_method duck
  duck.quack
  duck.feathers
end
 
def game
  donald = Duck.new
  person = Person.new
  test_method donald
  test_method person
end

game

Output of the above program:

Quaaaaaack!
The duck has feathers.
The person imitates a duck.
Person has no feather.

In a non-duck-typed language, one can create a function that takes an object of type Duck/Person and calls that object's walk and feathers methods. In a duck-typed language as shown above, the equivalent function would take an object of any type and call that object's walk and feathers methods. If the object does not have the methods that are called then the function signals a run-time error.

References

<references />