In this article, we’re going to talk about the Blocks in Ruby: Procs and Lambdas.
What are procs and lambdas?
1 2 3 4 5 6
| a_proc = Proc.new { puts "yeah!" } a_proc.call
a_lambda = lambda { puts "yeah!" } a_lambda = -> { puts "yeah!" } a_lambda.call
|
While it looks like these are all very similar, there are subtle differences that I will cover below.
Differences between procs and lambdas
- Lambdas check the number of arguments, while procs do not
1 2 3 4 5
| a_proc = Proc.new { |s| puts "yeah!" } a_proc.call
a_lambda = lambda { |s| puts "yeah!" } a_lambda.call
|
- Lambdas and procs treat return keyword differently
1 2 3 4 5 6 7 8 9 10 11 12
| def test_proc Proc.new { return 1 }.call return 0 end
def test_lambda lambda { return 1 }.call return 0 end
puts test_proc puts test_lambda
|
As you can see, the proc returned from the test_proc
method, and the lambda didn’t.
Passing a block to a method in different ways
- With the & (ampersand) symbol :
1 2 3 4 5 6 7 8
| def a_method(arg, &block) puts arg block.call end
a_method('Hi') { puts "I'm a Proc!" }
|
1 2 3 4 5 6 7 8
| def a_method(arg) puts arg yield end
a_method('Hi') { puts "I'm a Proc!" }
|