Haris Krajina
Haris Krajina

Reputation: 15296

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

Upvotes: 3

Views: 565

Answers (2)

Jörg W Mittag
Jörg W Mittag

Reputation: 369633

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

Upvotes: 1

Tsunamis
Tsunamis

Reputation: 6240

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".

Upvotes: 1

Related Questions