Reputation: 33
I know that hash doesn't store duplicate keys. But I want to know if that default behaviour can be changed according to requirement, Is that possible? I will give the sample code here
keys_array = [ 'key1', 'key2' ]
values_array = [
{"A": { "id": "1" }},
{"B": { "id": "2" }}
]
results = keys_array.zip(values_array ).to_h
Here output is exactly what I wanted
{"key1"=>{:A=>{:id=>"1"}}, "key2"=>{:B=>{:id=>"2"}}}
But If the keys get repeated , for example
keys_array = [ 'key1', 'key1' ] in which 'key1' key is repeated,
result will be {"key1"=>{:B=>{:id=>"2"}}}
But I want
{"key1"=>{:A=>{:id=>"1"}}, "key1"=>{:B=>{:id=>"2"}}}
I know about grouping and all , but it will change the result format
So I don't want to use that
I want this result {"key1"=>{:A=>{:id=>"1"}}, "key1"=>{:B=>{:id=>"2"}}}
where key1 is a repeated key.
Also please note that these array values are not fixed , its dynamic
Greatly appreciate your help!
Upvotes: 2
Views: 873
Reputation: 80065
You can alter the behavior of a hash with compare_by_identity.
h = Hash.new.compare_by_identity
h["key1"] = 1
h["key1"] = 2
p h #=> {"key1"=>1, "key1"=>2}
I've never seen a useful way for this.
Upvotes: 3
Reputation: 369468
The data structure you are looking for is called a multimap. It is, of course, possible to implement one in Ruby. You just have to do it. (Or find a library that does it for you.)
However, neither the core nor the standard library contain a multimap implementation.
Upvotes: 1
Reputation: 1930
No way with a hash, you could use an array of hashes instead:
[{"key1"=>{:A=>{:id=>"1"}}}, {"key1"=>{:B=>{:id=>"2"}}}]
Upvotes: 0