Sonntag, 6. Juli 2014

Have a lambda! ... a Ruby closure

First of all a lambda is one of the Ruby ways of implementing a closure. A closure makes a copy of its lexical environment, extended with the argument values bound to the function's formal parameters. Thus the body of the function in this new environment can be evaluated.
Since in Ruby everything is an object, a lambda is also one. It is just a Proc object, but with a different flavor:
lambda { return 'lambda' }
=> #
Please note the "(lambda)" in the stringified object.
In an example the original code:
class Array
  def aggregate
    self.inject(0) { |result, number| result += yield(number) }
  end
end
can be used like:
numbers = [1, 2, 3]
numbers.aggregate { |number| number ** 2 }
=> 14
If the passed block logic has to be used over and over again, a storing that logic into a variable solves the problem of duplicating the code:
squaring_lambda = lambda { |number| number ** 2 }
=> #
The Array#aggregate has to be made ready for passing a lambda by adding the new parameter and sending the Proc#call message:
class Array
  def aggregate block
    self.inject(0) { |result, number| result += block.call(number) }
  end
end
Using the instantiated lambda:
numbers = [1, 2, 3]
numbers.aggregate squaring_lambda
=> 14
and this lambda (which is a Proc object) can be reused as many as ...
The domain of a lambda is the same as the Proc's domain:
  1. wherever a block is required
  2. the block logic has to be duplicated (reused)

Further articles of interest:

Supported by Ruby 2.1.1