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.
Basic usage
Object or not
Block
is not an object, cannot execute directly, it need to be passed to a methodProc
andLambda
are 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 function
which is passed in parameter field. -
Proc
andLambda
: 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
:return
cannot be used within a block. Here is an article about blockbreak
andnext
behavioursLambda
:return
instruction within a block only suspend instruction execute within the block. It does not suspend outer method.Process
:return
instruction also affect the outer scope. It suspends the outer method directly.
Checking number of arguments passing to block, process, lambda
Reference
-
Adam Waxman, What Is the Difference Between a Block, a Proc, and a Lambda in Ruby?
-
StackOverFlow, Return behavior in block