Ruby blocks are not first-class

In terms of language design, why aren't ruby ​​blocks first-class?

Similarly, I think the blocks should be lambdas, thereby eliminating the need for cumbersome syntax like proc {...}. call or & proc or lambda or Proc.new. It will also save you the need for productivity.

+7
source share
2 answers

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.

+6
source

lambda and proc (and the block) have different semantics. Procs / blocks have non-local returns and are less picky about arity; lambdas are more like methods in their behavior. In my opinion, this distinction is useful and procs / blocks / lambdas should NOT be unified in your opinion.

+2
source

All Articles