Ruby:如何在不创建新实例的情况下检查实例方法的参数?

时间:2011-07-16 14:12:12

标签: ruby

在Ruby 1.9.2中,您可以使用方法(:symbol)检查任何方法的参数。如何在不创建新车的情况下检查Car#initialize方法?

class Car
  def initialize(fuel_type, passenger_capacity, door = 3)
    puts "TODO"
  end
end

Car.new(nil,nil).method(:initialize).parameters
  #=> [[:req, :fuel_type], [:req, :passenger_capacity], [:opt, :door]]

Instance_eval无效:

Car.instance_eval { |x| p x.method(:initialize).parameters } #=> [[:rest]]

1 个答案:

答案 0 :(得分:9)

Car.instance_method(:initialize).parameters
# => [[:req, :fuel_type], [:req, :passenger_capacity], [:opt, :door]]