我试着:
somearray = ["some", "thing"]
anotherarray = ["another", "thing"]
somearray.push(anotherarray.flatten!)
我预期的
["some", "thing", "another", "thing"]
但有
["some", "thing", nil]
我试着:
somearray = ["some", "thing"]
anotherarray = ["another", "thing"]
somearray.push(anotherarray.flatten!)
我预期的
["some", "thing", "another", "thing"]
但有
["some", "thing", nil]
当前回答
["some", "thing"] + ["another", "thing"]
其他回答
(array1 + array2).uniq
这样你就可以先得到array1元素。你不会得到副本。
如果新数据可以是数组或标量,并且如果它是数组,则希望防止新数据嵌套,splat操作符非常棒!它为标量返回一个标量,为数组返回一个已解压的参数列表。
1.9.3-p551 :020 > a = [1, 2]
=> [1, 2]
1.9.3-p551 :021 > b = [3, 4]
=> [3, 4]
1.9.3-p551 :022 > c = 5
=> 5
1.9.3-p551 :023 > a.object_id
=> 6617020
1.9.3-p551 :024 > a.push *b
=> [1, 2, 3, 4]
1.9.3-p551 :025 > a.object_id
=> 6617020
1.9.3-p551 :026 > a.push *c
=> [1, 2, 3, 4, 5]
1.9.3-p551 :027 > a.object_id
=> 6617020
最简洁的方法是使用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之前自动将多维数组平展。
我很惊讶没有人提到reduce,当你有一个数组的数组时,它工作得很好:
lists = [["a", "b"], ["c", "d"]]
flatlist = lists.reduce(:+) # ["a", "b", "c", "d"]
我发现更容易推入或追加数组,然后将它们压平,如下所示:
somearray = ["some", "thing"]
anotherarray = ["another", "thing"]
somearray.push anotherarray # => ["some", "thing", ["another", "thing"]]
#or
somearray << anotherarray # => ["some", "thing", ["another", "thing"]]
somearray.flatten! # => ["some", "thing", "another", "thing"]
somearray # => ["some", "thing", "another", "thing"]