(Don't Use)
a persistent local variable scope which holds on to local variables even after the code execution has moved out of that block.
function makeCounter () {
var count = 0;
return function () {
count += 1;
return count;
}
}
var x = makeCounter();
x(); returns 1
x(); returns 2
A block is code that is implicitly passed to a method
Convention: use {...} for single line blocks, and do...
end for multi-line blocks.
array = [1,2,3,4]
array.map! do |n|
n * n
end
=> [1, 4, 9, 16]
array = [1,2,3,4]
array.map! { |n| n * n }
=> [1, 4, 9, 16]
yield: It defers the execution of the method in order to evaluate the block.
The yield statement can also accept parameters, which are then passed into and evaluated within the block.
class Array
def map
self.each_with_index do |value, index|
self[index] = yield(value)
end
end
end
#pass it to any method that accepts a callable object.
class Array
def map!(proc_object)
self.each_with_index do |value, index|
self[index] = proc_object.call(value)
end
end
end
number_squared = Proc.new { |n| n * n }
array = [1,2,3,4]
array.map!(number_squared)
=> [1, 4, 9, 16]
*Note: We no longer use the yield keyword; instead, we directly use the call method on the Proc object, passing it the value from the array.
lambo = lambda { "I'm a lambda" }
lambo.call
=> "I'm a lambda"
lambo.call('arg')
ArgumentError: wrong number of arguments (1 for 0)
Lambda function are almost identical to Procs but with two key differences.
A lambda checks the the number of arguments it receives and returns an ArgumentError if they do not match.
Lambdas provide diminutive returns – meaning that when a Proc encounters a return statement in it’s execution, it halts the method and returns the provided value. Lambdas on the other hand, return their value to the method, allowing it to continue
def proc_math
Proc.new { return 1 + 1 }.call
return 2 + 2
end
def lambda_math
lambda { return 1 + 1 }.call
return 2 + 2
end
proc_math # => 2
lambda_math # => 4
Conclusion
In this study, we've covered the key differences between Blocks, Procs, and Lambdas