将哈希值分配给对象的 DRY 方法 [英] DRY way to assign hash values to an object
问题描述
我正在寻找一种优雅的方式将存储在 Hash 中的值分配给预先存在的对象.需要明确的是,如果我有一个对象,比如有两个属性的 obj,比如名字和年龄,我想从散列中分配这个值,而不需要执行以下操作:
I'm looking for a elegant way to assign the value stored inside an Hash into a pre-existed object. Just to be clear, if I have an object, say obj with two attributes, say name and age, I want to assign this values coming from an hash without do something like:
obj.name = hash[:name]
obj.age = hash[:age]
感谢您的关注.西蒙娜
推荐答案
最好的办法可能是简单地定义一个像 update_attributes
这样的方法,它接受一个散列并在类的实例方法中执行它.
Best bet is probably to simply define a method like update_attributes
which takes a hash and does it inside an instance method of the class.
扩展其他人所写的内容以及您似乎需要的内容,我认为您最好的选择是:
Expanding on what others have written and what you seem to need I think your best bet would be:
hash.keys.each do |key|
m = "#{key}="
obj.send( m, hash[key] ) if obj.respond_to?( m )
end
这将说明:
- 始终没有在哈希中包含类的所有属性,并且
- 散列中任意数量的键(不仅仅是:name 等)
这篇关于将哈希值分配给对象的 DRY 方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!