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

305
Views
Ruby creating a new hash from an array of key, value
first_response = [
  {"xId" => "123", "yId" => "321"}, 
  {"xId" => "x",   "yId" => "y"  }
]

first_response.each do |resp|
  x_id = resp['xId']
  y_id = resp['yId']
  puts x_id.to_s
  puts y_id.to_s
end                                                              
                                                                      

This gives me outputs

123
321
x
y  
                                                                       

output hash I want to create is {123=>{321}, x=>{y}}

first service: I have an array of hash that has two different ids example:(x_id and y_id) (there would be multiple pairs like that in the response)

I want to create a hash that should contain the matching pair of x_id and y_ids that we get from the first service with x_id's as the key for all the pairs.

over 4 years ago · Santiago Trujillo
2 answers
Answer question

0

If you know every hash in first_response is going to contain exactly two key/value pairs, you can extract their values and then convert that result into a hash (see Enumerable#to_h):

first_response.to_h(&:values)
# {"123"=>"321", "x"=>"y"}
over 4 years ago · Santiago Trujillo Report

0

Looks like this approach works, but I am not completely sure if that is right

first_response = [{"xId"=>"123","yId"=> "321"}, {"xId"=>"x","yId"=> "y"}]                         
h = {}.tap do |element|
  first_response.each do |resp|
    x_id = resp['xId']
    y_id = resp['yId']
    element[x_id] = y_id
  end
end
puts h.to_s
# {"123"=>"321", "x"=>"y"}                                      
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!