Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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
like image 820
Haris Krajina Avatar asked Dec 18 '25 15:12

Haris Krajina


1 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
like image 171
Jörg W Mittag Avatar answered Dec 21 '25 06:12

Jörg W Mittag



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!