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?


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

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]]