我需要获取给定块所需的参数数量。例如:
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 /扩展模块。
答案 0 :(得分:29)
当您使用&实现块时,它将成为Proc对象,其具有arity
方法。要小心 - 如果proc采用* splat arg,它会返回一个补码。
def foobar(x, y, z, &block)
p block.arity
end
(通过“Ruby编程语言”一书回答。)
答案 1 :(得分: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
另见codahale.com的A Ruby HOWTO: Writing A Method That Uses Code Blocks