我有一个以下形式的二维数组:
[ [(, (, (, (, (,],
[1.0,1.0,1.0,1.0,1.0,],
[+, +, +, +, +,],
[2.0,2.0,2.0,2.0,2.0,],
[), ), ), ), )]
]
即整数和数学字符的混合。我想要做的是将其转换为一维数组中的一系列字符串,例如:
[ (1+2), (1+2), (1+2), (1+2), (1+2) ]
有没有办法通过加入来做到这一点?
您可以使用transpose,然后加入转置数组的元素(我已经修改了数字以清楚地显示正在发生的事情):
# edited to add a transpose with map, thank you @Mladen
# edited to get rid of <<'s, thank you @tokland
# assumption:
a = [ ['(', '(', '(', '(', '('],
[1.1, 1.2, 1.3, 1.4, 1.5],
['+', '+', '+', '+', '+'],
[2.1, 2.2, 2.3, 2.4, 2.5],
[')', ')', ')', ')', ')'] ]
# transpose:
b = []
a.transpose.each { |c| b.push c.join }
# or, transpose with map:
b = a.transpose.map { |c| c.join }
# test:
puts b.inspect
其中有一个输出:
["(1.1+2.1)", "(1.2+2.2)", "(1.3+2.3)", "(1.4+2.4)", "(1.5+2.5)"]