|
|
Procs and Lambdas are similar to blocks in that they
too are anonymous functions.
|
|
Hence why we have procs and lambdas. They are proper object representations of a ruby block. |
|
Here’s how you create a block that’s a proc: |
|
And here’s how you’ll call this proc that’s assigned to a variable: |
|
You can also call it in these other shorthand ways: |
|
Here’s how you create a block that’s a lambda: |
|
The words |
|
You can use the “stabby lambda” syntax |
|
Converting a block to a procWhen a function is passed a block, and if that block needs to be passed as argument to yet another function, then you’ll have to convert the passed-in block to a proc.That’s done by defining a variable for it and prefixing it with & .
|
|
Function |
|
|
|
|
|
|
|
Converting a proc to a block |
|
Let’s say the |
|
Then, in |
|
Procs vs LambdasProcs and Lambdas differ in how they treat the arguments and the keywordsreturn and break .For the most part, you don’t have to worry about this. Just stick with lambdas if you don’t want to be caught by any surprises. Check the “Lambda and non-lambda semantics” section of the official doc for the differences. |
Next example: Regular Expressions.