在初始化时使用 attr_accessor 设置 ruby 2.0 关键字参数 [英] Set ruby 2.0 keyword arguments with attr_accessor on initialize
本文介绍了在初始化时使用 attr_accessor 设置 ruby 2.0 关键字参数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
如何动态设置而不必全部编写相同的代码.
How can I dynamically set without having to write the same code all over.
现在的代码是这样的:
def initialize(keywords: keywords, title: title, url: url, adsetting: adsetting)
self.keywords = keywords
self.title = title
self.url = url
self.adsetting = adsetting
end
如果列表变长,这很快就会失控.
If the list gets longer this quickly gets out of hand.
在 ruby 1.9 中,我只需将哈希值传递给该方法.像这样:
With ruby 1.9 I'd just pass a hash to the method. Like this:
def initialize(args)
args.each do |k,v|
instance_variable_set("@#{k}", v) unless v.nil?
end
end
但我更喜欢使用 Ruby 2.0 关键字参数.可以实现类似的目标吗?
def initialize(keywords: keywords, title: title, url: url, adsetting: adsetting)
args.each do |k,v|
instance_variable_set("@#{k}", v) unless v.nil?
end
end
推荐答案
def initialize(keywords: nil, title: nil, url: nil, adsetting: nil)
local_variables.each do |k|
v = eval(k.to_s)
instance_variable_set("@#{k}", v) unless v.nil?
end
end
或遵循 John Ledbetter 和 Cary Swoveland 的建议:
or following John Ledbetter and Cary Swoveland's suggestion:
def initialize(keywords: nil, title: nil, url: nil, adsetting: nil)
method(__method__).parameters.each do |type, k|
next unless type == :key
v = eval(k.to_s)
instance_variable_set("@#{k}", v) unless v.nil?
end
end
这篇关于在初始化时使用 attr_accessor 设置 ruby 2.0 关键字参数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文