你如何在 Ruby 中将一个数组添加到另一个数组而不是得到多维结果?

问题描述:

somearray = ["some", "thing"]

anotherarray = ["another", "thing"]

somearray.push(anotherarray.flatten!)

我预料到了

["some","thing","another","thing"]

你有一个可行的想法,但 #flatten! 是在错误的地方——它压平了它的接收器,所以你可以用它把[1, 2, ['foo', 'bar']] 变成[1,2,'foo','bar'].

You've got a workable idea, but the #flatten! is in the wrong place -- it flattens its receiver, so you could use it to turn [1, 2, ['foo', 'bar']] into [1,2,'foo','bar'].

我无疑忘记了一些方法,但您可以连接:

I'm doubtless forgetting some approaches, but you can concatenate:

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