我试过:
somearray = ["some", "thing"]
anotherarray = ["another", "thing"]
somearray.push(anotherarray.flatten!)
我以为
["some", "thing", "another", "thing"]
但是得到了
["some", "thing", nil]
最佳答案
你有一个可行的想法,但是 #flatten!
放错了地方——它压扁了它的接收器,所以你可以用它来转动 [1, 2, ['foo', 'bar']]
到 [1,2,'foo','bar']
。
我无疑忘记了一些方法,但你可以连接:
a1.concat a2
a1 + a2 # creates a new array, as does a1 += a2
或前置/附加:
a1.push(*a2) # note the asterisk
a2.unshift(*a1) # note the asterisk, and that a2 is the receiver
或拼接:
a1[a1.length, 0] = a2
a1[a1.length..0] = a2
a1.insert(a1.length, *a2)
或附加并展平:
(a1 << a2).flatten! # a call to #flatten instead would return a new array
关于ruby - 如何在 Ruby 中将一个数组添加到另一个数组而不以多维结果结束?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/1801516/