the-bass
the-bass

Reputation: 745

Find out if a Ruby object implements a method that accepts a certain amount of arguments

I want to find out if I can call a method count with exactly 0 arguments:

@object.count()

on @object without raising an error. Is there a method that can give me that information?

In case there isn't, is anything wrong with implementing it like so:

begin
  count = @object.count()
  # Do anything with the information
rescue ArgumentError => e
end

Upvotes: 3

Views: 596

Answers (3)

Pascal
Pascal

Reputation: 8656

First: Checking the number of arguments of a method sounds like there is something wrong. Second you are looking for "arity":

@object.method(:count).arity

Before you might want to check if the object responds to the given method.

@object.respond_to?(:count) && @object.method(:count).arity == 0

Be aware that if the method takes a variable number of arguments the arity is not that intuitive:

For Ruby methods that take a variable number of arguments, returns -n-1, where n is the number of required arguments. For methods written in C, returns -1 if the call takes a variable number of arguments.

Upvotes: 3

Jörg W Mittag
Jörg W Mittag

Reputation: 369633

We can rephrase the question as: does the method have any required parameters? Or: Are none of the parameters required?

@object.method(:count).parameters.none? {|type, _| [:req, :keyreq].include?(type) }

This will allow you to catch methods which have optional parameters with default arguments, methods which have optional keyword parameters with default values, and methods which have optional rest parameters.

I find parameters much easier to deal with than the heavily overloaded single integer return value of arity.

Upvotes: 3

Andrew Schwartz
Andrew Schwartz

Reputation: 4657

You want the arity method:

@object.method(:count).arity

http://ruby-doc.org/core-2.2.0/Method.html#method-i-arity

Upvotes: 0

Related Questions