Empresas
Empleos
  • Sobre nosotros
  • Soluciones
    • Publicación de vacantes
      Publica tu vacante y recibe candidatos calificados en 48h.
    • Evaluación de candidatos
      500+ pruebas técnicas y psicológicas, más anti-fraude.
    • Headhunting
      Búsqueda ejecutiva a la medida de principio a fin.
    • Nómina + EOR
      Dispersión de nómina y EOR en más de 15 países de LATAM.
  • Precios
  • Empleos

0

148
Vistas
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 Respuestas
Responde la pregunta

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 Denunciar

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 Denunciar

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 Denunciar
Responde la pregunta
Encuentra empleos remotos

¡Descubre la nueva forma de encontrar empleo!

Top de empleos
Top categorías de empleo
Empresas
Publicar vacante Precios Comercial
Legal
Términos y condiciones Política de privacidad
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomiéndame algunas ofertas
Necesito ayuda