Friday, February 25, 2011

Ruby : Methods, Procs and Lambdas

Started reading understanding Ruby blocks, Procs and Lambdas from a link in a rails post. Very very interesting.

I learnt what blocks are, Proc object is, and the subtle difference between the Proc and Lambdas. The differences aren't many and visible, but they are interesting.

1. Proc doesn't check number of arguments while Lambdas do
2. Use lambdas to pass the 'return' keyword as a part of an argument - Ruby doesn't allow you to do that in Proc

The 2nd point is because Procs are 'drop in code snippets and not methods', but lambdas act like methods.
Lambdas are anonymous way to write methods.
To use a named lambda use the Method object and assign the code to it.

eg      puts method(:square).class

No comments:

Post a Comment