我试着:

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

我预期的

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

但有

["some", "thing", nil]

当前回答

(array1 + array2).uniq

这样你就可以先得到array1元素。你不会得到副本。

其他回答

试试这个,它将结合你的数组删除重复

array1 = ["foo", "bar"]
array2 = ["foo1", "bar1"]

array3 = array1|array2

http://www.ruby-doc.org/core/classes/Array.html

进一步的文档请参阅“Set Union”

这里有两种方法,注意在这个例子中,第一种方法分配一个新数组(转换为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"]

Somearray = ["some", "thing"]

Anotherarray = ["another", "thing"]

Somearray + anotherarray

最简洁的方法是使用array# concat方法;它不会创建一个新数组(不像array# +会做同样的事情,但创建一个新数组)。

直接从文档(http://www.ruby-doc.org/core-1.9.3/Array.html#method-i-concat):

concat (other_ary) 将other_ary的元素追加到self。

So

[1,2].concat([3,4])  #=> [1,2,3,4]  

如果作为参数传入多维数组,array# concat将不会平展多维数组。你需要单独处理:

arr= [3,[4,5]]
arr= arr.flatten   #=> [3,4,5]
[1,2].concat(arr)  #=> [1,2,3,4,5]

最后,您可以使用我们的corelib gem (https://github.com/corlewsolutions/corelib),它为Ruby核心类添加了有用的帮助程序。特别地,我们有一个array# add_all方法,它将在执行concat之前自动将多维数组平展。

只是另一种方法。

[somearray, anotherarray].flatten
=> ["some", "thing", "another", "thing"]