Difference between block and &block in Ruby

前端 未结 3 1728
执笔经年
执笔经年 2021-01-30 01:47

Why sometimes I should use block and other times &block inside functions that accept blocks?

3条回答
  •  南方客
    南方客 (楼主)
    2021-01-30 02:16

    If you don't set the & before block, Ruby won't recognize it's relationship to the "block" you pass to the function. Here some examples.

    def f(x, block); end
    f(3) { 2+2 }    # gives an error, because "block" is a
                    # regular second argument (which is missing)
    
    def g(x, &block); end
    g(3) { 2+2 }    # legal
    
    def h(x); end
    h(3) { 2+2 }    # legal
    

    For later use in a function:

    def x(&block)   # x is a 0 param function
      y(block)      # y is a 1 param function (taking one "Proc")
      z(&block)     # z is a 0 param function (like x) with the block x received
    end
    

    So, if you call z(&block) it's (nearly!!) the same as calling z { yield }: You just pass the block to the next function.

提交回复
热议问题