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 => 14and 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:
- wherever a block is required
- the block logic has to be duplicated (reused)
Further articles of interest:
Supported by Ruby 2.1.1
Keine Kommentare:
Kommentar veröffentlichen