How do I force the same hash value for different object instantiations in RoR?

时间:2017-07-10 15:28:01

标签: ruby-on-rails hash ruby-on-rails-5

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.

1 个答案:

答案 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