Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

255
Views
Duplicate keys of hash in ruby

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!

over 4 years ago · Santiago Trujillo
3 answers
Answer question

0

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.

over 4 years ago · Santiago Trujillo Report

0

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.

over 4 years ago · Santiago Trujillo Report

0

No way with a hash, you could use an array of hashes instead:

[{"key1"=>{:A=>{:id=>"1"}}}, {"key1"=>{:B=>{:id=>"2"}}}]
over 4 years ago · Santiago Trujillo Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!