如何动态设置,而无需编写相同的代码.
现在的代码看起来像这样:
def initialize(keywords: keywords,title: title,url: url,adsetting: adsetting) self.keywords = keywords self.title = title self.url = url self.adsetting = adsetting end
如果列表变长,这很快就会失控.
用红宝石1.9我只是传递一个哈希的方法.喜欢这个:
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,adsetting: adsetting) args.each do |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)的建议:
def initialize(keywords: 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