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

147
Visualizações
How to map nested array to the second attribute in the array in ruby

Sorry for the poor title, I just don't know how to express what I want here without examples.

I have the following

[
  [ [1,2], true ],
  [ [3,4], false ]
]

and I want to get

[
  [1, true],
  [2, true],
  [3, false],
  [4, false]
]

Is there any clean way to do this in ruby?

over 4 years ago · Santiago Trujillo
3 Respostas
Responde à pergunta

0

You can use a combination of flat_map on the outer array and map on the inner array. Something like:

arr = [
  [ [1,2], true ],
  [ [4,5], false ]
]

arr.flat_map do |nums, val|
  nums.map {|num| [num, val]}
end
over 4 years ago · Santiago Trujillo Relatório

0

You could use Array#map and Array#product:

arr = [
  [ [1,2], true ],
  [ [3,4], false ]
].flat_map { |(arr, bool)| arr.product([bool]) }
# [[1, true], [2, true], [3, false], [4, false]]
over 4 years ago · Santiago Trujillo Relatório

0

Using Enumerable#each_with_object

ary =
  [
    [[1, 2], true],
    [[3, 4], false]
  ]

ary.each_with_object([]) do |(nums, boolean), new_ary|
  nums.each { |num| new_ary << [num, boolean] }
end

# => [[1, true], [2, true], [3, false], [4, false]]
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