Summary of block, process and lambda in Ruby
There are three ways to group trunk of code in Ruby which are block,
process and lambda. Each of them behave differently from others. This post
is all about the differences of them and its examples and use cases.
|-------------------------+--------------------+-------------+------------------------|
| Characteristics | Process | Block | Lambda |
|-------------------------+--------------------+-------------+------------------------|
| Object | yes | no | yes |
|-------------------------+--------------------+-------------+------------------------|
| Number of arguments* | many | 1 | many |
|-------------------------+--------------------+-------------+------------------------|
| Checking number of args | no | identifying | yes |
|-------------------------+--------------------+-------------+------------------------|
| Return behavior | affect outer scope | identifying | not affect outer scope |
|-------------------------+--------------------+-------------+------------------------|Basic usage
# block
def test_function(&a)
a.call
end
test_function {
p "it's block"
}
# lambda
lam = lambda{
p "it's lambda"
}
lam.call #OR#
test_function(lam)
# Process
pro = Proc.new {
p "it's proc"
}
pro.call #OR#
test_function(pro)Object or not
Blockis not an object, cannot execute directly, it need to be passed to a methodProcandLambdaare objects, its instance can be execute directly
Number of block, proc and lambda passed in parameter field
-
Block: A method can use only one block which passed in the parameter fields. Well, obviously, block is a kind of anonymous function. If there are two passing in parameter field. How could interpreter understand when should it use this or that block. Meanwhile, a method can only use one block oranonymous functionwhich is passed in parameter field. -
ProcandLambda: In fact, these two are identical and it’s object instances. On the other words, you are passing object in parameter field. Hence, pass them as many as you want.
Return behaviour
Block:returncannot be used within a block. Here is an article about blockbreakandnextbehavioursLambda:returninstruction within a block only suspend instruction execute within the block. It does not suspend outer method.Process:returninstruction also affect the outer scope. It suspends the outer method directly.
Checking number of arguments passing to block, process, lambda
|-------+-------+---------+--------|
| | Block | Process | Lambda |
|-------+-------+---------+--------|
| check | no | no | yes |
|-------+-------+---------+--------|Reference
-
Adam Waxman, What Is the Difference Between a Block, a Proc, and a Lambda in Ruby?
-
StackOverFlow, Return behavior in block