Ruby: Blocks
What is a Block?
A block is a chunk of code that runs to produce an outcome. We have seen them a lot so far. A block is not a method, but can exist within one, or outside of it. A block is not an object either, an exception to Ruby’s “Everything is an Object” rule. Yeah, they lied! Blocks can be identified by their syntax of do...end
or are between curly braces {}
. An example might be:
So a block is not a method, but can be passed to one with the #yield
method. This can be done like so:
The method there is called harry_meet_sally
and exists between the def
and end
. The method is an object, and can be called again and again. The yield
within the method is calling the block that exists outside of it. The #yield
method can also be used with parameters, like so:
Notice here that when yield
is called with the name
parameter it finds "Tahm Kench"
in the block and calls it within the message. Next yield
is passed "Sally"
which overrides "Tahm Kench"
.