Ruby 1.8.7中方法的可选参数数

时间:2012-09-10 10:43:43

标签: ruby ruby-on-rails-3.1

不确定是否有答案,但希望有人知道。我正在尝试的是获取Ruby 1.8.7中的方法的可选参数的数量。 Method#arity将无效,因为它返回-n-1,其中n是方法所需参数的数量。我需要的是可选参数的数量? e.g。

def foo(a,b,c=4,d=3)
  # ...
end

如何识别 2个可选参数?请记住,这是 Ruby 1.8.7

更新

道歉问题不明确,我需要在调用方法之前知道可选参数的数量。 e.g。

method_def = self.instance_method(:foo)
# check for number of args
# call method if it meets some kind of criteria

2 个答案:

答案 0 :(得分:1)

您可以将方法定义为:

def foo(a,b,*p)
  number_of_arguments = p.size

  c = p[0]
  d = p[1]      
end

可在“可选参数”下找到here的更多信息。

答案 1 :(得分:1)

我认为你不能。事实上,我认为这是在Ruby 1.9中引入{Proc, Method, UnboundMethod}#parameters的原因之一:

instance_method(:foo).parameters.count {|type,| type == :opt }
# => 2