If you’ve been learning how to develop software in Ruby, you are probably familiar with blocks (closures). Blocks are statements that are fed into method calls as arguments which then executes those statements. Here’s an example of a block given to a popular ruby method.
In this post, we’re going to introduce Proc and lambdas. A Proc is similar to a block in that it also is a statement or statements, but unlike a block which are like anonymous functions, Proc
is a ruby class and new procs are instances of the class.
As you can see, we create a new Proc object that defines a block of code. We call the proc with call
and supply it with an argument 'Hello World'
which is then passed on the block defined by the proc.
Similar to a proc, ruby also has lambda
. A lambda is a special kind of Proc
. One of the differences between a lambda and a regular proc is that a lambda have argument number restrictions. A proc can be supplied with more arguments than required, but lambda’s will throw errors that the number of arguments is off.
Another key difference with proc and lambda is that returns work a little differently in each. Lambda returns from it self while procs returns from the method. Lets check this behavior with some examples
And the same as a proc
In my next post, I’ll go into how Procs and lambdas can be used to pass data between scopes.