In terms of language design, why aren't ruby blocks first-class?
Mostly for performance reasons, as far as I know. Consider:
def test_yield yield end def test_block &block block.call end la = lambda {} def test_lambda l l.call end
Then compare with the empty block for the first two, and the third with the new la for the call or with the same la , and notice how much faster the yield goes in each case. The reason is that the explicit & block variable creates a Proc object, like a lambda, but simply does not.
A side effect (which I actually found to use in order to recursively pass transferred blocks using the proc object), you cannot give in to proc or lambda outside of any covering area:
foo = proc { yield if block_given? } foo.call { puts 'not shown' } def bar baz = proc { yield if block_given? } baz.call end bar { puts 'should show' }
Is it because I realized this (I lost a lot of hair because of this until it started to tick), block_given? is sent to main when foo calls it, and disallows bases when it receives an estimate in the bar.
Denis de bernardy
source share