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 do |x|
    closure_value = x
  end, do
    closure_value += 1
  end, do
one, two, three = create_closure
myval = 21
puts " == #{}"
puts " == #{}"
puts " == #{}"
puts " == #{}"

This outputs:

learning about closures == 21 == 22 == 23 == 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

Note: Only a member of this blog may post a comment.