Reputation: 107
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?
Upvotes: 1
Views: 335
Reputation: 33420
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]]
Upvotes: 1
Reputation: 15248
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]]
Upvotes: 0
Reputation: 7740
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
Upvotes: 0