我试着:
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]
当前回答
Somearray = ["some", "thing"]
Anotherarray = ["another", "thing"]
Somearray + anotherarray
其他回答
你可以使用+运算符!
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"]
(array1 + array2).uniq
这样你就可以先得到array1元素。你不会得到副本。
你有一个可行的想法,但#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
如果新数据可以是数组或标量,并且如果它是数组,则希望防止新数据嵌套,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