Lambdas vs. Blocks
A lambda is a piece of code that you can store in a variable, and is an object. The simplest explanation for a block is that it is a piece of code that can't be stored in a variable and isn't an object. It is, as a consequence, significantly faster than a lambda, but not as versatile and also one of the rare instances where Ruby's "everything is an object" rule is broken.
As with most things in programming, there is more to this story, but blocks are an advanced topic so lets keep things simple for now. If you're interested in studying blocks in more detail, take a look at our chapter on blocks in our book "Ruby Primer: Ascent" which addresses intermediate and advanced topics.
Let's look at an example of a block that does the same thing as the lambda you wrote in the previous exercise.
Let's list the ways in which this example is different from the last exercise that we did when learning about lambdas.
- There's no
lambda
. - There's something new called
yield
. - There's a method that has the body of a lambda immediately after the parameter list, which is a little weird.