我试着:
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]
当前回答
详细阐述@Pilcrow的答案,对于大型数组唯一合适的答案是concat(+),因为它速度快,并且在循环中操作时不会分配一个新对象来进行垃圾回收。
下面是基准:
require 'benchmark'
huge_ary_1 = Array.new(1_000_000) { rand(5_000_000..30_000_00) }
huge_ary_2 = Array.new(1_000_000) { rand(35_000_000..55_000_00) }
Benchmark.bm do |bm|
p '-------------------CONCAT ----------------'
bm.report { huge_ary_1.concat(huge_ary_2) }
p '------------------- PUSH ----------------'
bm.report { huge_ary_1.push(*huge_ary_2) }
end
结果:
user system total real
"-------------------CONCAT ----------------"
0.000000 0.000000 0.000000 ( 0.009388)
"------------------- PUSH ----------------"
example/array_concat_vs_push.rb:13:in `block (2 levels) in <main>': stack level too deep (SystemStackError)
正如你所看到的,当数组足够大时,使用push会抛出ERROR:堆栈级别太深(SystemStackError)。
其他回答
这里有两种方法,注意在这个例子中,第一种方法分配一个新数组(转换为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"]
a = ['a', 'b']
b = ['c', 'd']
arr = [a, b].flatten
这不会去除dups,但是
a|b
删除重复。
我很惊讶没有人提到reduce,当你有一个数组的数组时,它工作得很好:
lists = [["a", "b"], ["c", "d"]]
flatlist = lists.reduce(:+) # ["a", "b", "c", "d"]
你可以使用+运算符!
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
["some", "thing"] + ["another", "thing"]