大佬教程收集整理的这篇文章主要介绍了ruby – 有没有办法知道一个方法需要多少个参数?,大佬教程大佬觉得挺不错的,现在分享给大家,也给大家做个参考。
"Name".methods
但是,如果我想知道特定方法需要多少参数,那么我该如何实现呢?我的意思是有什么办法(通过在irb上打一些命令),我们可以获得特定方法的参数数量(而不是引用文档)?
.methods只返回方法名称,而不是方法参数列表.
Method#arity
:
"String".method(:Strip).arity # => 0
从Ruby文档:
所以,例如:
# Variable number of arguments,one is required def foo(a,*b); end method(:foo).arity # => -2 # Variable number of arguments,none required def bar(*a); end method(:bar).arity # => -1 # Accepts no argument,implemented in C "0".method(:to_f).arity # => 0 # Variable number of arguments (0 or 1),implemented in C "0".method(:to_i).arity # => -1
更新我刚刚发现了Method#parameters
的退出,这可能是非常有用的:
def foo(a,*b); end method(:foo).parameters # => [[:req,:a],[:rest,:b]]
以上是大佬教程为你收集整理的ruby – 有没有办法知道一个方法需要多少个参数?全部内容,希望文章能够帮你解决ruby – 有没有办法知道一个方法需要多少个参数?所遇到的程序开发问题。
如果觉得大佬教程网站内容还不错,欢迎将大佬教程推荐给程序员好友。
本图文内容来源于网友网络收集整理提供,作为学习参考使用,版权属于原作者。
如您有任何意见或建议可联系处理。小编QQ:384754419,请注明来意。