Monday, April 18, 2011

Blocks, Procs and Lambdas

I was able to google around and get a wealth of information regarding Ruby blocks, Procs and Lambdas - closures in Ruby.

blocks vs Procs

Block: Your method is breaking an object down into smaller pieces, and you want to let your users interact with these pieces.
Block: You want to run multiple expressions atomically, like a database migration.
Proc: You want to reuse a block of code multiple times.
Proc: Your method will have one or more callbacks.

unlike Procs, lambdas check the number of arguments passed.
lambdas have diminutive returns
Part of Ruby’s syntax is that arguments (a Proc in this example) cannot have a return keyword in it.
The neat thing is that this Method object will act just like a lambda, because the concept is the same. This method however, is a named method (called square) while lambdas are anonymous methods.

Thanks Robert Sosinsky 

No comments:

Post a Comment