Obtaining number of block parameters

后端 未结 2 2010
粉色の甜心
粉色の甜心 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 12:08

    Is this what you're looking for...

    def foobar(x, y, z, &block)
      # need to obtain number of arguments in block
      # which would be 3 in this example
      case block.arity
        when 0 
          yield "i have nothing"
        when 1
          yield "I got ONE block arg"
        when 2
          yield "I got TWO block args"
        when 3
          yield "I got THREE block args"
      end
    end
    
    foobar(1,2,3) { |a, b, c|
        puts a
    }
    

    Outputs:

    D:\ruby\bin>ruby -v
    ruby 1.8.6 (2007-09-24 patchlevel 111) [i386-mswin32]
    
    D:\ruby\bin>ruby c:\Temp.rb
    I got THREE block args
    

    See also - A Ruby HOWTO: Writing A Method That Uses Code Blocks from codahale.com

提交回复
热议问题