Home > other >  Ruby creating a new hash from an array of key, value
Ruby creating a new hash from an array of key, value

Time:12-05

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.

CodePudding user response:

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

CodePudding user response:

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