我试着:
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]
当前回答
(array1 + array2).uniq
这样你就可以先得到array1元素。你不会得到副本。
其他回答
我发现更容易推入或追加数组,然后将它们压平,如下所示:
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"]
Somearray = ["some", "thing"]
Anotherarray = ["another", "thing"]
Somearray + anotherarray
你有一个可行的想法,但#flatten!在错误的地方——它会使接收器变平,所以你可以用它把[1,2,['foo', 'bar']]变成[1,2,'foo','bar']。
毫无疑问,我忘记了一些方法,但你可以串联起来:
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)
或append和flatten:
(a1 << a2).flatten! # a call to #flatten instead would return a new array
a = ["some", "thing"]
b = ["another", "thing"]
将b追加到a并将结果存储在a中:
a.push(*b)
or
a += b
在这两种情况下,a都变成:
["some", "thing", "another", "thing"]
但在前一种情况下,b的元素被追加到现有的a数组中,在后一种情况下,两个数组连接在一起,结果存储在a中。
只是另一种方法。
[somearray, anotherarray].flatten
=> ["some", "thing", "another", "thing"]