Take the following class:
class Automator
def fill_specific_form(fields)
fields.each_pair do |key, value|
puts "Setting '#{key}' to '#{value}'"
end
end
end
a = Automator.new
a.fill_specific_form :first_name => "Mads", :last_name => "Mobæk"
# => Setting 'first_name' to 'Mads'
# => Setting 'last_name' to 'Mobæk'
Is it possible to do the same without a hash? Since all parameters are required, I want a method with the following signature:
fill_specific_form(first_name, last_name)
In my mind this would be possible by having the method body reflect and iterate over its parameters, thus achieving the same result.
How would you implement this? Does a pattern/idiom for this exist already? Two obvious benefits would be parameter information in IDEs and not having to check if all hash keys are supplied.
What I want to avoid is:
puts "Setting first_name to #{first_name}"
puts "Setting last_name to #{last_name}"
# and so on
If you set no other local variables inside the method,
local_variableswill give you a list of the method’s parameter names (if you do set other variables you can just calllocal_variablesfirst thing and remember the result). So you can do what you want withlocal_variables+eval:Be however advised that this is pure evil.
And at least for your example
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 yourfields.each_paircode.