2

I have this array:

[[["a", "c"], "e"],
 [["a", "c"], "f"],
 [["a", "c"], "g"],
 [["a", "d"], "e"],
 [["a", "d"], "f"],
 [["a", "d"], "g"],
 [["b", "c"], "e"],
 [["b", "c"], "f"],
 [["b", "c"], "g"],
 [["b", "d"], "e"],
 [["b", "d"], "f"],
 [["b", "d"], "g"]]

I would like to turn it into this:

[["a", "c", "e"],
 ["a", "c", "f"],
 ["a", "c", "g"],
 ["a", "d", "e"],
 ["a", "d", "f"],
 ["a", "d", "g"],
 ["b", "c", "e"],
 ["b", "c", "f"],
 ["b", "c", "g"],
 ["b", "d", "e"],
 ["b", "d", "f"],
 ["b", "d", "g"]]

How can I do this with Ruby? I have looked at flatten by it seems to work from the outside in, not inside out.

Josh Petitt
  • 9,371
  • 12
  • 56
  • 104
  • 1
    You might want to look into why you're getting the array in the first form rather than the second. When I see data in the first form it's usually because I did something wrong and need to rethink my code. – the Tin Man Jun 24 '13 at 16:08
  • @theTinMan, good point. I am getting the data in that form as a result of the product call. I'll post the call syntax to show how it was generated. – Josh Petitt Jun 24 '13 at 17:01
  • That works. Often we see questions dealing with a symptom as someone seeks a bandage, when the real problem needs a bit of refactoring or a different approach which ends up fixing a lot of other code. – the Tin Man Jun 24 '13 at 18:35
  • @theTinMan, I created a separate question here: http://stackoverflow.com/questions/17286499/how-to-create-permutation-of-an-array-using-values-from-sub-arrays – Josh Petitt Jun 24 '13 at 22:59

2 Answers2

8

You could use flatten and map:

ar.map! {|i| i.flatten}
 # => [["a", "c", "e"],
 #     ["a", "c", "f"],
 #     ["a", "c", "g"],
 #     ["a", "d", "e"],
 #     ["a", "d", "f"],
 #     ["a", "d", "g"],
 #     ["b", "c", "e"],
 #     ["b", "c", "f"],
 #     ["b", "c", "g"],
 #     ["b", "d", "e"],
 #     ["b", "d", "f"],
 #     ["b", "d", "g"]]

Another one-liner would be :

 ar.map!(&:flatten)

 # => [["a", "c", "e"],
 #     ["a", "c", "f"],
 #     ["a", "c", "g"],
 #     ["a", "d", "e"],
 #     ["a", "d", "f"],
 #     ["a", "d", "g"],
 #     ["b", "c", "e"],
 #     ["b", "c", "f"],
 #     ["b", "c", "g"],
 #     ["b", "d", "e"],
 #     ["b", "d", "f"],
 #     ["b", "d", "g"]]
Arup Rakshit
  • 116,827
  • 30
  • 260
  • 317
4

or try arr.each {|i| i.flatten!}

leonhart
  • 1,193
  • 6
  • 12
  • That depends on whether you want a destructive or a non-destructive version. OMG's answer is a non-destructive one. – John Dvorak Jun 24 '13 at 05:16
  • 2
    @JanDvorak yes, but op said "I would like to turn it into this", so i think the original won't be needed – leonhart Jun 24 '13 at 05:21
  • Thanks, I chose this one cause I don't need the original. I wish I could give half a check to both answers. Thanks everyone. – Josh Petitt Jun 24 '13 at 12:26
  • 2
    @JoshPetitt If you don’t need original then you can use also `ar.map! {|i| i.flatten}`. It will destroy the original one. – Arup Rakshit Jun 24 '13 at 14:20