質問

I am playing with introspection and would like to extract argument count and argument names at runtime. Would it be possible to implement something like this?

class Greeter
   def self.greet(name, weekday = "Friday")
     "Hello #{name}. Today is #{weekday}"
   end

   def self.splatter(*arguments)
     arguments.join("|")
   end
end

Greeter.argument_count(:greet)
=> 1..2

Greeter.argument_names(:greet)
=> [:name, :weekday]

Greeter.argument_count(:splatter)
=> [0..Infinity]

I have no idea on how to retrieve the names of the arguments.

I have however managed to extract the arguments count by by deliberately invoking the method with a flood of random arguments solely to trigger ArgumentError and then extract the permitted number of arguments from the exception message. However, this is dangerous and does not work for splat method signatures.

役に立ちましたか?

解決

There is an established format for these things. You can modify the following to meet your needs.

class Object
  def argument_count m; method(m).arity end
  def argument_names m; method(m).parameters end
end

Greeter.argument_count(:greet) # => -2
Greeter.argument_names(:greet) # => [[:req, :name], [:opt, :weekday]]
ライセンス: CC-BY-SA帰属
所属していません StackOverflow
scroll top