Reflection on method parameters in Ruby

前端 未结 3 653
青春惊慌失措
青春惊慌失措 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:48

    I don't quite understand. Do you want to receive all parameters within a single array?

    def fill_specific_form *args
        #Process args
    end
    
    0 讨论(0)
  • 2020-12-12 07:55

    If you set no other local variables inside the method, local_variables will give you a list of the method's parameter names (if you do set other variables you can just call local_variables first thing and remember the result). So you can do what you want with local_variables+eval:

    class Automator
      def fill_specific_form(first_name, last_name)
        local_variables.each do |var|
          puts "Setting #{var} to #{eval var.to_s}"
        end
      end
    end
    
    Automator.new().fill_specific_form("Mads", "Mobaek")
    

    Be however advised that this is pure evil.

    And at least for your example

    puts "Setting first_name to #{first_name}"
    puts "Setting last_name to #{last_name}"
    

    seems much more sensible.

    You could also do fields = {:first_name => first_name, :last_name => last_name} at the beginning of the method and then go with your fields.each_pair code.

    0 讨论(0)
  • 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.

    0 讨论(0)
提交回复
热议问题