Procs and Lambdas
I am a big believer in fundamentals and foundation. In grade school I was horrific in Spanish. Being close to failing and having to repeat the previous years Spanish class, my parents sent me to summer school. I learned the fundamentals of the language and went into the following year understanding concepts which I didn't have the tools to comprehend previously.
We were told a quote early on in the semester which has stuck with me. It was along the lines of, "The problem isn't with Rails, but with your Ruby." I took away to truly understand Rails was to truly understand the fundaments and the foundation that Rails was built on.
Before diving into Proc and Lambdas which I saw as one of those fundamentals/building blocks of the Ruby language, we must go over what a Block is first.
Blocks
A block is a block of code or a code block, thus the name block. A list of instructions for your code to follow. Blocks can be identified by do...end or { }. There is a saying in Ruby land that everything in Ruby is an object, however that does not apply here. A block is not an object! Which brings us to procs and lambdas.
Procs
Proc, stands for procedure, is a block of code which is an object. This means procs can be passed through in method arguments, be something a method returns and have methods called upon them.
1 2 3 4 5 |
|
Up until now we mostly been using blocks in enumerables. Procs can take the place of blocks in enumerables.
1 2 |
|
But lets say you don’t want to just pass in 1 value. Using an iterator now seems to not be the right tool for the job. There is the call method.
1 2 3 4 5 |
|
Another benefit procs over blocks is that they can be returned.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 |
|
Lambda
A lambda is also a block of code which is an object. This is because a lambda is apart of the Proc class.
1 2 3 4 5 6 7 |
|
Procs vs Lambdas
1 - Procs and lambdas treat arguments differently. Procs do not check for the correct number or arguments while lambdas do.
1 2 3 4 5 6 |
|
2 - Proc and lambdas treat returns differently. A return inside a proc will be treated as a return for the entire method which it is inside, while a return inside a lambda will only be treated as the return for inside the lambda.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 |
|
&
1 2 3 4 |
|
Additional Examples
1 2 3 4 5 6 7 8 |
|