Number of optional arguments for a method in Ruby 1.8.7

Not sure that there is an answer for this but hope somebody know. What I am trying is to get number of optional arguments for a Method in Ruby 1.8.7. Method#arity will not work since it returns -n-1, where n is number of required arguments of method. What I need is number of optional arguments? e.g.

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

How can I identify that there are 2 optional arguments? Keep in mind this is Ruby 1.8.7

UPDATE

Apologies question was not clear, I need to know number of optional arguments before calling the method. e.g.

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

Answers


I don't think you can. In fact, I think that was one of the reasons for the introduction of {Proc, Method, UnboundMethod}#parameters in Ruby 1.9:

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

You can define your method like:

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

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

Further information can be found here under "Optional Arguments".


Need Your Help

series object not callable with linear regression in python

python scikit-learn linear-regression statsmodels

I am new to Python and I am trying to build a simple linear regression model. I am able to build the model and see the results, but when I try to look at the parameters I get an error and I am not ...

About UNIX Resources Network

Original, collect and organize Developers related documents, information and materials, contains jQuery, Html, CSS, MySQL, .NET, ASP.NET, SQL, objective-c, iPhone, Ruby on Rails, C, SQL Server, Ruby, Arrays, Regex, ASP.NET MVC, WPF, XML, Ajax, DataBase, and so on.