Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

308
Visualizações
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 Respostas
Responde à pergunta

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 Relatório

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 Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda