获取块参数数量 [英] Obtaining number of block parameters

查看:76
本文介绍了获取块参数数量的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我需要获取给定块采用的参数数量.例如:

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 number of arguments in block
  # which would be 3 in this example
end

这可能在1.9中继中实现,但在任何正式版本中均不可行.我希望有什么方法可以做到而不必下载单独的gem/extension模块.

This is possible in the 1.9 trunk, but not in any official release. I was hoping if there's any way to do this without having to download a separate gem/extension module.

推荐答案

使用&实现块时,它将成为Proc对象,该对象具有arity方法.请注意-如果proc带有* splat arg,它将返回一个人的补码.

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

(通过"The Ruby Programming Language"一书回答.)

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

这篇关于获取块参数数量的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆