CSC/ECE 517 Fall 2012/ch1 1w4 aj

From Expertiza_Wiki
Revision as of 20:50, 14 September 2012 by Avranade (talk | contribs)
Jump to navigation Jump to search

Introduction

Closures

Code Blocks

Before understanding the concept of Closures, let us take a brief introduction on “Code Blocks” in Ruby. A code block is a chunk of code, Ruby statements and expressions written between curly braces { } or between “do…end”. For example:

 {  puts "Hello World!"  }

or

  do
     3.times(puts "Hello")
     object1.call
  end

Generally, as per Ruby standard, braces are used for single-line blocks and do...end for multiline blocks. Also, braces have a higher preference than do/end. A code block may appear only immediately after a method is invoked. If a method has parameters, then the block will look as follows:

 random_method("John") { puts "How you doing? " }


What is a Closure?

Now, a block can use local variables from the surrounding scope. Such blocks are called Closures. Let us look at a simple example:

def closurefunc()
     lambda {|val| val + inc }
  end

  p1 = closurefunc(3)
  p1.call(1)    # => 4
 
  p2 = closurefunc(8)
  p2.call(5)   # => 13

In the above example, the value ‘3’ is assigned to the local variable inc of method closurefunc and value ‘1’ is assigned to inner variable val.