CSC/ECE 517 Fall 2011/ch3 4b js

From Expertiza_Wiki
Jump to navigation Jump to search

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