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

298
Visualizações
How to convert array of 3 element arrays in to a hash where key is first 2 elements

My problem is that I need to do efficient lookups of if a 2 element array and their corresponding value is nil. So if I have the following arrays:

arr1 = [
  [1, 2, 100],
  [3, 4, nil],
  [5, 6, 101]
]

I want something like

h = {
  [1, 2] => 100,
  [3, 4] => nil,
  [5, 6] => 101
}

So I can do something like:

error = []
arr2 = [
  [1,2],
  [3,4],
  [7,8]
]

arr2.each do |val|
  if h.include?(val)
    if h[val] == nil
      error << "Value is nil"
    else
      # Do something
    end
  else
    error << "Key doesn't exist"
  end
end
over 4 years ago · Santiago Trujillo
3 Respostas
Responde à pergunta

0

Given that overwriting or ignoring duplicates is acceptable per your comment.

You can use Enumerable#each_with_object to iterate the Array and create a Hash like so

arr1 = [
  [1, 2, 100],
  [3, 4, nil],
  [5, 6, 101],
  [1, 2, nil],
]

arr1.each_with_object({}) do |(*first_two,last),obj| 
  obj[first_two] = last
end 
#=> {[1, 2]=>nil, [3, 4]=>nil, [5, 6]=>101}

You can ignore duplicates in a similar fashion

arr1.each_with_object({}) do |(*first_two,last),obj| 
  obj[first_two] = last unless obj.key?(first_two)
end 
#=> {[1, 2]=>100, [3, 4]=>nil, [5, 6]=>101}

Explanation:

  • each_with_object({}) will pass each element of of arr1 to the block along with an object (a Hash in this case)

  • (*first_two,last),obj - *first_two will collect everything up to last and obj is our Hash

  • obj[first_two] = last simple Hash key assignment

  • each_with_object returns the object (obj Hash in this case)

Update as recommended by @Stefan in ruby >= 2.7 you could also use

arr1.to_h {|*first_two,last| [first_two, last] }

This version will overwrite keys

over 4 years ago · Santiago Trujillo Relatório

0

arr1 = [
[1, 2, 100],
[3, 4, nil],
[5, 6, 101]
]

result = {}
arr1.each { |i| result[i.first(2)] = i.last }

=> {[1, 2]=>100, [3, 4]=>nil, [5, 6]=>101}
over 4 years ago · Santiago Trujillo Relatório

0

You can destructure every subarray during mapping and then convert result to hash with Array#to_h method

arr1 = [
  [1, 2, 100],
  [3, 4, nil],
  [5, 6, 101],
  [1, 2, nil],
]

arr1.map { |*first_two, last| [first_two, last] }.to_h
# => {[1, 2]=>nil, [3, 4]=>nil, [5, 6]=>101}

Duplicates will be overwritten

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