不确定是否有答案,但希望有人知道。我正在尝试的是为 Ruby 1.8.7 中的方法获取可选参数的数量。 Method#arity
将不起作用,因为它返回 -n-1
,其中 n
是方法所需参数的数量。我需要的是可选参数的数量?例如
def foo(a,b,c=4,d=3)
# ...
end
我如何确定有 2 个可选参数?请记住,这是 Ruby 1.8.7
更新
抱歉,问题不清楚,我需要在调用该方法之前知道可选参数的数量。例如
method_def = self.instance_method(:foo)
# check for number of args
# call method if it meets some kind of criteria
最佳答案
我认为你做不到。事实上,我认为这是在 Ruby 1.9 中引入 {Proc, Method, UnboundMethod}#parameters
的原因之一:
instance_method(:foo).parameters.count {|type,| type == :opt }
# => 2
关于ruby - Ruby 1.8.7 中方法的可选参数数量,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12350031/