Obtaining number of block parameters

后端 未结 2 2015
粉色の甜心
粉色の甜心 2021-02-14 11:38

I need to obtain the number of parameters a given block takes. For example:

foobar(1,2,3) { |a, b, c|
}

def foobar(x, y, z, &block)
  # need to obtain numbe         


        
2条回答
  •  广开言路
    2021-02-14 11:54

    When you materialize a block with &, it becomes a Proc object, which has an arity method. Just be careful - it returns the one's complement if the proc takes a *splat arg.

    def foobar(x, y, z, &block)
      p block.arity
    end
    

    (Answer via "The Ruby Programming Language" book.)

提交回复
热议问题