我试着:
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]
当前回答
适用于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]
其他回答
Somearray = ["some", "thing"]
Anotherarray = ["another", "thing"]
Somearray + anotherarray
如果新数据可以是数组或标量,并且如果它是数组,则希望防止新数据嵌套,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
somearray = ["some", "thing"]
anotherarray = ["another", "thing"]
somearray + anotherarray # => ["some", "thing", "another", "thing"]
somearray.concat anotherarray # => ["some", "thing", "another", "thing"]
somearray.push(anotherarray).flatten # => ["some", "thing", "another", "thing"]
somearray.push *anotherarray # => ["another", "thing", "another", "thing"]
我发现更容易推入或追加数组,然后将它们压平,如下所示:
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"]
适用于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]