3 ms·
Basically. But Ruby has two types of lambdas, one called lambda, and one called proc. Blocks act like the second type. The difference is that if return is call
by vidarh 1y ago
Basically. But Ruby has two types of lambdas, one called lambda, and one called proc. Blocks act like the second type.
The difference is that if return is called in the former, you return to the expression after where it is called, while I'm the latter return returns from the scope where it is defined.
This is usually going to feel reasonably intuitive, but can become weird if you e.g. reify a block into a named object and pass it around.
It can be very useful though. E.g. you can pass a block down into a recursive algorithm as a means to do a conditional early exit when a given criteria is met.
Notably you can do this even if a piece of code takes a named argument instead of a block and doesn't anticipate that use and expect you to pass a lambda instead of a process...
In most of the typical uses of a block, most people will just naturally expect the behaviour you see, because the block looks and feels like part of the scope it will return from.