Summary of block, process and lambda in Ruby
There are three ways to group trunk of code in Ruby which are
lambda. Each of them behave differently from others. This post
is all about the differences of them and its examples and use cases.
Object or not
Blockis not an object, cannot execute directly, it need to be passed to a method
Lambdaare 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 or
anonymous functionwhich is passed in parameter field.
Lambda: 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.
returncannot be used within a block. Here is an article about block
returninstruction within a block only suspend instruction execute within the block. It does not suspend outer method.
returninstruction also affect the outer scope. It suspends the outer method directly.
Checking number of arguments passing to block, process, lambda
Adam Waxman, What Is the Difference Between a Block, a Proc, and a Lambda in Ruby?
StackOverFlow, Return behavior in block