Blocks, Procs and Lambdas





Below are some simple examples which will help highlight the differences between Blocks, Procs amd Lambdas.





Blocks are very common Ruby elements. For example;

            Block





Procedures or Procs for short are blocks that we can call again. If we call class on proc we will see that it is a proc object.
Notice if we call proc.call(2) we get 2, while proc.call is nil and proc.call(1,2,3) is 1 (the first number called, the other numbers get ignored).

Calling proc_check prints nothing.


            Proc



Lambdas are variations on Procs. If we call class on lambda we will see that it is also a proc object.
One key difference is that if we call lambda.call(2) we get 2, while lambda.call and lambda.call(1,2,3) both raise ArgumentErrors.

Calling lambda_check prints 'I am a Lambda!!' because return triggers the puts right after the lam.call.

            Proc




Resources

http://www.reactive.io/tips/2008/12/21/understanding-ruby-blocks-procs-and-lambdas/


http://rubylearning.com/satishtalim/ruby_blocks.html


http://rubymonk.com/learning/books/4-ruby-primer-ascent/chapters/18-blocks/lessons/64-blocks-procs-lambdas


http://awaxman11.github.io/blog/2013/08/05/what-is-the-difference-between-a-block/