# 数组合并（联合）

``#<Article id: 1, xml_document_id: 1, source: "<article><domain>events.waikato.ac</domain><excerpt...", created_at: "2010-02-11 01:32:46", updated_at: "2010-02-11 01:41:28" >` `

` `A => [1, 2, 3, 4, 5] B => [3, 4, 5, 6, 7] A.magic_merge(B) #=> [1, 2, 3, 4, 5, 6, 7]` `

### 4 Solutions collect form web for “数组合并（联合）”

` `require 'benchmark' a1 = []; a2 = [] [a1, a2].each do |a| 1000000.times { a << rand(999999) } end puts "Merge with pipe:" puts Benchmark.measure { a1 | a2 } puts "Merge with concat and uniq:" puts Benchmark.measure { (a1 + a2).uniq } puts "Concat only:" puts Benchmark.measure { a1 + a2 } puts "Uniq only:" b = a1 + a2 puts Benchmark.measure { b.uniq }` `

` `Merge with pipe: 1.000000 0.030000 1.030000 ( 1.020562) Merge with concat and uniq: 1.070000 0.000000 1.070000 ( 1.071448) Concat only: 0.010000 0.000000 0.010000 ( 0.005888) Uniq only: 0.980000 0.000000 0.980000 ( 0.981700)` `

` `require "set" require "benchmark" a1 = []; a2 = [] [a1, a2].each do |a| 1000000.times { a << rand(999999) } end s1, s2 = Set.new, Set.new [s1, s2].each do |s| 1000000.times { s << rand(999999) } end puts "Merge with pipe:" puts Benchmark.measure { a1 | a2 } puts "Merge with concat and uniq:" puts Benchmark.measure { (a1 + a2).uniq } puts "Concat only:" puts Benchmark.measure { a1 + a2 } puts "Uniq only:" b = a1 + a2 puts Benchmark.measure { b.uniq } puts "Using sets" puts Benchmark.measure {s1 + s2} puts "Starting with arrays, but using sets" puts Benchmark.measure {s3, s4 = [a1, a2].map{|a| Set.new(a)} ; (s3 + s4)}` `

（对于ruby1.8.7（2008-08-11 patchlevel 72）[universal-darwin10.0]）

` `Merge with pipe: 1.320000 0.040000 1.360000 ( 1.349563) Merge with concat and uniq: 1.480000 0.030000 1.510000 ( 1.512295) Concat only: 0.010000 0.000000 0.010000 ( 0.019812) Uniq only: 1.460000 0.020000 1.480000 ( 1.486857) Using sets 0.310000 0.010000 0.320000 ( 0.321982) Starting with arrays, but using sets 2.340000 0.050000 2.390000 ( 2.384066)` `

` `require 'benchmark' def reset_arrays! @array1 = [] @array2 = [] [@array1, @array2].each do |array| 10000.times { array << ActiveSupport::SecureRandom.hex } end end reset_arrays! && puts(Benchmark.measure { @array1 | @array2 }) # => 0.030000 0.000000 0.030000 ( 0.026677) reset_arrays! && puts(Benchmark.measure { @array1.concat(@array2) }) # => 0.000000 0.000000 0.000000 ( 0.000122)` `

` `a = [1,2,3,3,2] b = [1,2,3,4,3,2,5,7] (a+b).uniq` `
• 骨干model.destroy（）调用错误callback函数，即使它工作正常？
• 如何将Ruby类名转换为下划线符号？
• 尝试安装pg gem时找不到'libpq-fe.h头文件
• 你如何在Rails 3中使用ActiveRecord关联？
• 如何拯救OmniAuth :: Strategies :: OAuth2 :: CallbackError？
• Rails：around_ *callback
• 我如何testingRails迁移？
• 是否有可能在MiniTest中将testing标记为挂起？
• gem更新后：testing失败，“资产没有被宣布在生产中预编译”
• ActiveRecord，has_many：through和Polymorphic Associations
• Rails使用块进行部分渲染