In Ruby, following are the two ways in which we can pass a block to a method:
- As an argument
- As an anonymous block
Passing an argument is always considered better then anonymous block for various reasons:
- It increases readability of the method.
- If we pass block as an argument, then we get
And in comparision to object, we can not do much with anonymous block.
Let’s define a method that calls a
If we call this method without a block,
then we’ll get
We’ll also get
ArgumentError if we use
lambda instead of
To handle this error, we need to explicitly add
Because method doesn’t tell us to pass anonymous block.
That is why, Ruby 2.7 has added
warning for Proc.new and proc without block in a method called with a block and errors
for lambda without block in a method called with a block.
We do not get any warning when Proc.new and proc is used
without block in a method in earlier versions.
We get a warning when lambda is used without block in a method.
With Ruby 2.7, We will get a warning for Proc.new and proc
without block in a method called with a block.
It will give error for lambda without block in a method called with a block.