Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to flatten innermost array

Tags:

ruby

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.

like image 511
Josh Petitt Avatar asked Jul 26 '26 10:07

Josh Petitt


1 Answers

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"]]
like image 120
Arup Rakshit Avatar answered Jul 28 '26 00:07

Arup Rakshit