Dev
Dev

Reputation: 21

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.

Upvotes: 1

Views: 521

Answers (2)

Dev
Dev

Reputation: 21

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"}                                      

Upvotes: 1

Sebastián Palma
Sebastián Palma

Reputation: 33481

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"}

Upvotes: 2

Related Questions