Blocks as Closures

Closures can be something difficult to grasp but they have some interesting use-cases from simple to harder ones. For instance:

def power_to
  foo = 1
  Proc.new { foo += foo }
end

proc_obj = power_to
puts proc_obj.call
puts proc_obj.call
puts proc_obj.call

This will print:

$ 2
$ 4
$ 8

The method power_to returns a Proc object which has the state of foo local variable. Though, the variable remains accessible to the block even if that variable is out of scope when the block is called again.

That’s closures and it’s the basis of lexical scoping which you can find in other programming languages such as JavaScript.

Advertisements
Tagged , , ,

2 thoughts on “Blocks as Closures

  1. Closures in Ruby have some particularities though, you’re only using Procs here, if you use lambdas its a whole new story and you need to beware of the differences.

    Here, check this code:

    def power_to
    foo = 1
    Proc.new do
    foo += foo
    return foo if foo > 3
    end
    end

    def power_to_lambda
    foo = 1
    lambda do
    foo += foo
    return foo if foo > 3
    end
    end

    lambda_obj = power_to_lambda
    lambda_obj.call
    p lambda_obj.call

    proc_obj = power_to
    proc_obj.call
    p proc_obj.call

    The lambda will print 4, as expected. When using the proc, you’ll get `unexpected return (LocalJumpError)`, that’s because lambdas are seen as methods, thus can have a return, and procs are seen as arguments, which in ruby cannot have returns.

    Here’s a good read on the subject: http://www.robertsosinski.com/2008/12/21/understanding-ruby-blocks-procs-and-lambdas/

    • davidcunha says:

      Thanks Luís.. I already knew that lambdas are like anonymous methods (checking number of arguments,etc). However I was unaware of the differences between lambdas and Procs regarding the return semantics.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

%d bloggers like this: