I'm using RoR 5.0.1. I have a model that is not persisted to a database. It has two fields
first_field
second_field
How do I force different instantiations of the object in which its fields have the same value to have the same hash value? Right now it seems each unique creation of an object has a different hash value, even if the individual attributes have the same values . So if I create two different objects
o1 = MyObject.new({:first_field => 5, :second_field => "a"})
o2 = MyObject.new({:first_field => 5, :second_field => "a"})
I'd like them to have the same hash values even though they are different instantiations of the object.
答案 0 :(得分:1)
您正在寻找的行为并非完全清楚您的问题。但是,如果您希望(正如Michael Gorman所要求的那样)MyObject
的实例共享相同的hash
实例(以便对值o1
的更改反映在{{1}的值中然后你可以做类似的事情:
o2
然后创建 class MyObject
def initialize(hsh = {})
@hsh = hsh
hsh.each do |k,v|
class_eval do
# define the getter
define_method(k) do
@hsh[k]
end
# define the setter
define_method("#{k}=") do |val|
@hsh[k] = val
end
end
end
end
end
的单个实例:
hash
使用此 hsh = {first_field: 5, second_field: "a"}
实例化您的两个对象:
hash
两个实例都具有相同的 o1 = MyObject.new(hsh)
o2 = MyObject.new(hsh)
值:
first_field
2.3.1 :030 > o1.first_field
=> 5
2.3.1 :031 > o2.first_field
=> 5
中的更改将反映在o1.first_field
:
o2.first_field
与 2.3.1 :033 > o1.first_field = 7
=> 7
2.3.1 :034 > o1.first_field
=> 7
2.3.1 :035 > o2.first_field
=> 7
相同:
second_field
由于动态生成 2.3.1 :037 > o1.second_field
=> "a"
2.3.1 :038 > o2.second_field
=> "a"
2.3.1 :040 > o1.second_field = "b"
=> "b"
2.3.1 :041 > o1.second_field
=> "b"
2.3.1 :042 > o2.second_field
=> "b"
和setter
,您可以执行以下操作:
getter
hsh = {first_field: 5, second_field: "a", nth_field: {foo: :bar}}
o1 = MyObject.new(hsh)
将回复o1
而无需在nth_field
上进行任何额外编码:
MyObject