Ruby 中方法参数的思考 [英] Reflection on method parameters in Ruby
问题描述
参加以下课程:
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.
您将如何实现这一点?是否已经存在这种模式/习语?两个明显的好处是 IDE 中的参数信息,并且不必检查是否提供了所有散列键.
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.
我想避免的是:
puts "Setting first_name to #{first_name}"
puts "Setting last_name to #{last_name}"
# and so on
推荐答案
如果你没有在方法内部设置其他局部变量,local_variables
会给你一个方法参数名称的列表(如果你设置了设置其他变量,您可以首先调用 local_variables
并记住结果).所以你可以用 local_variables
+eval
做你想做的事:
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.
至少对于你的例子
puts "Setting first_name to #{first_name}"
puts "Setting last_name to #{last_name}"
似乎更明智.
你也可以做 fields = {:first_name =>名字, :last_name =>last_name}
在方法的开头,然后使用您的 fields.each_pair
代码.
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.
这篇关于Ruby 中方法参数的思考的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!