Getting the arity

Hi,

I would like to get the arity of a method. However, arity is a method
of Method, and I can only get a Method from the method method of Object
(phew!).

So it appears impossible to get the arity of a method in a class
without making an instance of that class. Is this true?

A hypothetical use would be to print out all classes with their arity
at a given time during execution (and making dummy instances could
cause unwanted side-effects).

-qs

···

Do you Yahoo!?
Yahoo! SiteBuilder - Free, easy-to-use web site design software
http://sitebuilder.yahoo.com

Jeff Mitchell wrote:

I would like to get the arity of a method. However, arity is a method
of Method, and I can only get a Method from the method method of Object
(phew!).

So it appears impossible to get the arity of a method in a class
without making an instance of that class. Is this true?

Not in 1.8, where you can get an UnboundedMethod using instance_method:

String.instance_method(:replace).arity #=> 1
String.instance_method(:gsub).arity #=> -1

···


([ Kent Dahl ]/)_ ~ [ Kent Dahl - Kent Dahl ]/~
))_student_/(( _d L b_/ (pre-) Master of Science in Technology )
( __õ|õ// ) )Industrial economics and technological management(
_
/ö____/ (_engineering.discipline=Computer::Technology)

So it appears impossible to get the arity of a method in a class
without making an instance of that class. Is this true?

This is just an example

svg% cat b.rb
#!/usr/bin/ruby
class A
   def a(b)
   end

   def b(c, d)
   end
end

A.instance_methods(false).each do |m|
   p "#{m} : #{A.instance_method(m).arity}"
end
svg%

svg% b.rb
"b : 2"
"a : 1"
svg%

Guy Decoux

Jeff Mitchell wrote:

Hi,

I would like to get the arity of a method. However, arity is a method
of Method, and I can only get a Method from the method method of Object
(phew!).

So it appears impossible to get the arity of a method in a class
without making an instance of that class. Is this true?

A hypothetical use would be to print out all classes with their arity
at a given time during execution (and making dummy instances could
cause unwanted side-effects).

Here’s a starting point. Note that, of course, you get a lot more methods than you bargained for, because it will show you all the inherited methods, too.

Hope it helps.

···

def dump_methods(klass)
klass.methods.each do |name|
method = Fred.method(name)

  puts "#{name} arity #{method.arity}"

end
end

class Fred
def f(a, b, c)
end

def g(x)
end
end

dump_methods Fred

Hi,

···

In message “getting the arity” on 03/08/28, Jeff Mitchell quixoticsycophant@yahoo.com writes:

So it appears impossible to get the arity of a method in a class
without making an instance of that class. Is this true?

You can get UnboundMethod from a class, e.g.

p Regexp.instance_method(:match).arity

=> 1

						matz.