Sixth article in the Prepare for a Ruby job interview series. In this article, we’re going to talk about the Blocks in Ruby : Procs and Lambas.
Proc and Lambda are anonymous function that can be moved around in your code as variable.
pr = Proc.new { |a, b| a + b }
p pr.call(1, 2)
l = lambda { |a, b| a + b }
p l.call(1, 2)
The main difference between those is that a return statement in a proc will behave like a part of the calling method (and return from it) :
def test_proc
Proc.new { return 1 }.call
return 0
end
def test_lambda
lambda { return 1 }.call
return 0
end
p test_proc # => 1
p test_lambda # => 0
As you can see, the proc returned from the test_proc method.
Passing a block to a method can be done in different ways.
With the & (ampersand) symbol :
def super_method(arg1, &block)
p arg1
block.call
end
super_method('Hi!') { p "I'm a proc!" }
# => "Hi!"
# => "I'm a proc!"
With yield :
def super_method(arg1)
p arg1
yield
end
super_method('Hi!') { p "I'm a proc!" }
# => "Hi!"
# => "I'm a proc!"
You can also simply pass the block as an argument :
def super_method(arg1, pr)
p arg1
pr.call
end
pr = Proc.new { p "I'm a proc!" }
super_method('Hi!', pr)
# => "Hi!"
# => "I'm a proc!"
Checkout the next article about the Splat operator.