Monday, January 30, 2012

Learning about closures in ruby

Per Wikipedia, a closure is defined as: "In computer science, a closure (also lexical closurefunction closurefunction value or functional value) is afunction together with a referencing environment for the non-local variables of that function.[1] A closure allows a function to access variables outside its typical scope."

Taken on just its pure definition, it's a little difficult to conceptualize, especially for someone like me who comes from a mostly iterative programming background. So let's look at some sample code (I modified some sample code about Ruby from Wikipedia)



puts "learning about closures"
def create_closure(initial_value = 0)
  closure_value = initial_value
  return Proc.new do |x|
    closure_value = x
  end, Proc.new do
    closure_value += 1
  end, Proc.new do
    closure_value
  end
end
one, two, three = create_closure
myval = 21
puts "one.call(myval) == #{one.call(myval)}"
puts "two.call == #{two.call}"
puts "two.call == #{two.call}"
puts "three.call == #{three.call}"


This outputs:

learning about closures
one.call(myval) == 21
two.call == 22
two.call == 23
three.call == 23




Each proc here is a closure, because the scope of each proc is bound to the scope of where it was defined. In this case, all of the procs are bound to the scope of the create_closure function.

So you can see that even though the execution of create_closure is finished, each proc still has access to the same local closure_value variable that was defined within create_closure function.


No comments:

Post a Comment