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.
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"]]
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With