在 Ruby 中,我该怎么做:
[
1,
["green", "blue", "black"],
[ ["1", "2"], ["3"], ["4", "5"] ]
]
到这个?
[
[1, "green", "1"],
[1, "green", "2"],
[1, "blue", "3"],
[1, "black", "4"],
[1, "black", "5"],
]
我试过 .zip 但没有运气。非常感谢任何帮助,当然我正在寻找一种高性能的解决方案。
最佳答案
该模式对我来说并不完全清楚,但这将获得您提供的示例的预期输出:
data[1].
zip(data[2]).
flat_map { |x, ys| [x].product(ys) }.
map { |zs| [data[0], *zs] }
#=> [[1, "green", "1"], [1, "green", "2"], [1, "blue", "3"],
# [1, "black", "4"], [1, "black", "5"]]
关于arrays - Ruby:多维数组到一维行,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/46254694/