DEV Community

Felix Imbanga
Felix Imbanga

Posted on

Blocks, Procs, and Lambdas

Lambdas - nameless methods. This is how methods accept blocks using the yield keyword.

.collect method - returns a copy of a variable, doesn't change or mutate the original variable. ie .collect! in which the ! means this method can do something dangerous in ruby.

Blocks - these are one of the few exceptions of things that aren't objects in ruby. Bit of code between do or end or {}, but can be passed to methods like .each or .select.

Proc - a block which is saved to a variable. Good for keeping code DRY aka Dont Repeat Yourself.

To pass a proc to a method expecting a block use & right before the the parameter.

Procs are objects so they have the power/abilities of objects and can be called over and over. This prevents you from having to retype the contents of your block every-time you need to execute a particular block of code.

We can call procs directly by using ruby's .call method

Remember, in ruby there is always more than one way to do something.

I learned I cant puts a proc because it is an object not a string, this will print the memory address instead of a proc. procs are callable objects that contain blocks of code and to see the effect of the code within a proc, you must call it. Lambdas are also objects.

**Lambdas vs procs
Lambdas check the number of arguments passed to it while a proc does not. This means lambdas will give an error if you a pass it the wrong number of arguments. While a proc will ignore unexpected arguments and assign nil to any missing arguments.
When Lambdas return, control is passed back to the calling method. When a proc returns it does so immediately without going back to the calling method.
& is used to pass a lambda.
() and {} are important in the syntax of lambdas.

Top comments (0)