我有一個項目,我在一個類上動態創建屬性,這些屬性也作爲散列存儲在另一個屬性中,作爲所有這些屬性及其值的集合。我希望能夠做的是在更新散列時更新屬性,反之亦然。基於哈希更新的更新屬性
事情是這樣的:
class SomeClass
def initialize
#code that creates the attributes on the class
config_list.each { |config| self.class.send(:attr_accessor, config) }
end
#list of attributes that are dynamically added to the class
#this is normally read from a config file but I added it here to simplify
def config_list
[:abc, :def, :ghi]
end
def configuration
config_list.inject({}) do |r,e|
r[e] = instance_variable_get("@#{e.to_s}"); r
end
end
end
用法:
x = SomeClass.new
#=> #<SomeClass:0x007f9931990710>
x.abc = 5
#=> 5
x.configuration
#=> {:abc=>5, :def=>nil, :ghi=>nil}
x.configuration[:abc] = 10
#=> 10
x.abc
#=> 5
我想的是最後最後通話:
x.abc
返回10,因爲配置的值更新。那可能嗎?如果是這樣,我該怎麼做?
@engineersmnky將這項工作雖然兩者兼得?我希望「@configuration」在更新「@abc」時更新,當「@configuration」更新時更新「@abc」 –