Home > database >  How to map nested array to the second attribute in the array in ruby
How to map nested array to the second attribute in the array in ruby

Time:01-20

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?

CodePudding user response:

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

CodePudding user response:

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

CodePudding user response:

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]]
  •  Tags:  
  • Related