I have multiple classes that have the following two hash tables. Both mappings must have an identical set of keys. My problem is that there are many classes with this structure and that the key sets will change over time.
mapping_1 = {
:key_1 => "attr_1_1",
:key_2 => "attr_2_1",
:key_3 => "attr_3_1"
}
mapping_2 = {
:key_1 => "attr_1_2",
:key_2 => "attr_2_2",
:key_3 => "attr_3_2"
}
I need to be able to access the values given the keys for both mappings and the key from the value with mapping 1. In other words, I need to be able to perform these operations:
mapping_1[:key_1]
mapping_1.index("attr_2_1") #(Ruby 1.8.7)
mapping_2[:key_3]
Question: Is there a way where I wouldn’t have to duplicate writing the keys in both structures?
I thought of having the key map to an array( :key_1 => ["attr_1_1", "attr_1_2"] ) but this won’t work because when I run the command mapping_1.index() I don’t know what the value of the second attribute is.
I think you should definitely create your own hash class and use it instead of
Hash. It would take care of the keyset, and wrap per-object storage.It could have class methods to edit your keyset such as:
and instance methods that you would use in your container classes, which would mimick
Hashmethods:etc. You could use ordinary
Hashfor underlying storage, of course. If you need to be able to expand your keyset whenever you add a new key to any of the instances, just calladd_keyfromset.