我试着:
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]
当前回答
a = ["some", "thing"]
b = ["another", "thing"]
将b追加到a并将结果存储在a中:
a.push(*b)
or
a += b
在这两种情况下,a都变成:
["some", "thing", "another", "thing"]
但在前一种情况下,b的元素被追加到现有的a数组中,在后一种情况下,两个数组连接在一起,结果存储在a中。
其他回答
a = ['a', 'b']
b = ['c', 'd']
arr = [a, b].flatten
这不会去除dups,但是
a|b
删除重复。
这里有两种方法,注意在这个例子中,第一种方法分配一个新数组(转换为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
试试这个,它将结合你的数组删除重复
array1 = ["foo", "bar"]
array2 = ["foo1", "bar1"]
array3 = array1|array2
http://www.ruby-doc.org/core/classes/Array.html
进一步的文档请参阅“Set Union”
适用于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]