Reflection on method parameters in Ruby

前端 未结 3 654
青春惊慌失措
青春惊慌失措 2020-12-12 07:08

Take the following class:

class Automator
  def fill_specific_form(fields)
    fields.each_pair do |key, value|
      puts \"Setting \'#{key}\' to \'#{value}         


        
3条回答
  •  小蘑菇
    小蘑菇 (楼主)
    2020-12-12 07:56

    To reflect on a method's (or Proc's) parameters, you can use Proc#parameters, Method#parameters or UnboundMethod#parameters:

    ->(m1, o1=nil, *s, m2, &b){}.parameters
    # => [[:req, :m1], [:opt, :o1], [:rest, :s], [:req, :m2], [:block, :b]]
    

    However, in your case, I don't see why you need reflection, since you already know the names of the parameters anyway.

提交回复
热议问题