1

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?

2
  • Sorry, that was a typo. I edited with the fix Commented Jan 19, 2022 at 19:49
  • 1
    Another variation on a theme: arr.flat_map { |(x,y), bool| [[x,bool], [y,bool]] }. Notice that all the answers reproduce the array in your example. Had you assigned a variable to it (arr = [[[1, 2], true], [[3, 4], false]]) that would not have been necessary. For that reason it is advised to assign a variable to all inputs in examples given in questions. Commented Jan 19, 2022 at 20:26

3 Answers 3

1

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]]
Sign up to request clarification or add additional context in comments.

Comments

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

Comments

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

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.