Blocks, Procs and lambdas (also know as closures in Computer Science) are one of the most powerful aspects of Ruby, and also one of the most misunderstood. I will attempt to explains the similarities and differences.
A block is just a bit of code between do..end or {}. It's not an object on its own, but it can be passed to methods like .each or .collect.
We've seen this in action.
Nothing new here.
A proc is a saved block we can use over and over. Just like you can give a bit of code a name and turn it into a method, you can name a block and turn it into a proc. With procs you write your code once and use it many times. That way keeping your code D.R.Y (Don't Repeat Yourself).
Like procs lambdas are objects. With the exception of some syntax differences, procs and lamdas are essentially the same.
Eventhough procs and lambdas sport stricking similarities there are two main differences.
First, lambdas check the number of arguments, while procs do not.
In contrast, procs don’t care if they are passed the wrong number of arguments.
Second, Lambdas and procs treat the ‘return’ keyword differently.
‘return’ inside of a lambda triggers the code right outside of the lambda code
‘return’ inside of a proc triggers the code outside of the method where the proc is being executed