2009-07-03 26 views
10

我需要获得的参数的给定块需要的数量。例如:获得的块数参数

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

def foobar(x, y, z, &block) 
    # need to obtain number of arguments in block 
    # which would be 3 in this example 
end 

这可能在1.9中继,但不是在任何正式版本。我希望是否有办法做到这一点,而无需下载单独的gem /扩展模块。

回答

29

当您使用&实现块时,它将成为一个Proc对象,它具有一个arity方法。只要小心 - 如果proc采用* splat arg,它会返回补码。

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

(通过 “Ruby编程语言” 一书的答案)

+1

你打我吧:) +1 – Gishu 2009-07-03 04:44:50

+6

权。请注意`{||零}`将具有为0的元数,但`{零}`将具有-1的元数。 – 2009-07-03 04:48:45

8

这是你在找什么...

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 
} 

输出:

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 

又见 - A Ruby HOWTO: Writing A Method That Uses Code Blocks从codahale.com