我试着:

somearray = ["some", "thing"]
anotherarray = ["another", "thing"]
somearray.push(anotherarray.flatten!)

我预期的

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

但有

["some", "thing", nil]

当前回答

适用于Ruby版本>= 2.0但不适用于旧版本的简单方法:

irb(main):001:0> a=[1,2]
=> [1, 2]
irb(main):003:0> b=[3,4]
=> [3, 4]
irb(main):002:0> c=[5,6]
=> [5, 6]
irb(main):004:0> [*a,*b,*c]
=> [1, 2, 3, 4, 5, 6]

其他回答

你可以使用+运算符!

irb(main):001:0> a = [1,2]
=> [1, 2]
irb(main):002:0> b = [3,4]
=> [3, 4]
irb(main):003:0> a + b
=> [1, 2, 3, 4]

你可以在这里阅读关于数组类的所有内容: http://ruby-doc.org/core/classes/Array.html

这里有两种方法,注意在这个例子中,第一种方法分配一个新数组(转换为somearray = somearray + anotherarray)

somearray = ["some", "thing"]

anotherarray = ["another", "thing"]

somearray += anotherarray # => ["some", "thing", "another", "thing"]

somearray = ["some", "thing"]
somearray.concat anotherarray # => ["some", "thing", "another", "thing"]
["some", "thing"] + ["another", "thing"]
somearray = ["some", "thing"]
anotherarray = ["another", "thing"]
somearray + anotherarray # => ["some", "thing", "another", "thing"]
somearray.concat anotherarray # => ["some", "thing", "another", "thing"]
somearray.push(anotherarray).flatten # => ["some", "thing", "another", "thing"]
somearray.push *anotherarray # => ["another", "thing", "another", "thing"]
 

本质上,问题是“如何在Ruby中连接数组”。自然,答案是使用concat或+,几乎在每个答案中都提到过。

对这个问题的自然扩展是“如何在Ruby中按行执行2D数组的连接”。当我在谷歌上搜索“红宝石串联矩阵”时,这个SO问题是最上面的结果,所以我想我应该把我的答案留给后人(没有问过但相关的)。


在一些应用程序中,你可能想要按行“连接”两个2D数组。类似的,

[[a, b], | [[x],    [[a, b, x],
 [c, d]] |  [y]] =>  [c, d, y]]

这有点像“增广”矩阵。例如,我使用这种技术创建了一个邻接矩阵来表示一组较小的矩阵中的图。如果没有这种技术,我将不得不以一种容易出错或令人沮丧的方式迭代组件。例如,我可能不得不做一个each_with_index。相反,我将zip和flatten组合如下:

# given two multi-dimensional arrays that you want to concatenate row-wise
m1 = [[:a, :b], [:c, :d]]
m2 = [[:x], [:y]]

m1m2 = m1.zip(m2).map(&:flatten)
# => [[:a, :b, :x], [:c, :d, :y]]