在ruby中仅合并一个数组中两个数组的相应元素

你好,我在ruby中有以下两个数组

A=["a","b","c"] B=["d","e","f"] 

而且我想制作这个

 C = ["ad", "be", "cf"] 

无论数组长度如何。 但是这两个数组的长度始终相同。

有一个巧妙的方法来做到这一点? 我的意思是不是用for循环迭代数组。

使用Array#zipArray#map方法非常简单:

 A = ["a","b","c"] B = ["d","e","f"] A.zip(B).map { |a| a.join } # => ["ad", "be", "cf"] # or A.zip(B).map(&:join) # => ["ad", "be", "cf"] 

还有一种方式(但看起来不太好),:-)

 A.map.with_index { |e,i| e + B[i] } # => ["ad", "be", "cf"] 

作为zip的替代方案,如果两个数组不是相同的基数,则可以使用transpose引发exception。

 [A,B].transpose.map(&:join) 

只是为了记录,一个基准与不同的列出的解决方案。 结果:

  user system total real Map with index 1.120000 0.000000 1.120000 ( 1.113265) Each with index and Map 1.370000 0.000000 1.370000 ( 1.375209) Zip and Map {|a|} 1.950000 0.000000 1.950000 ( 1.952049) Zip and Map (&:) 1.980000 0.000000 1.980000 ( 1.980995) Transpose and Map (&:) 1.970000 0.000000 1.970000 ( 1.976538) 

基准

 require 'benchmark' N = 1_000_000 A = ["a","b","c"] B = ["d","e","f"] Benchmark.bmbm(20) do |x| x.report("Map with index") do N.times do |index| A.map.with_index { |e, i| e + B[i] } end end x.report("Each with index and Map") do N.times do |index| A.each_with_index.map { |e, i| e + B[i] } end end x.report("Zip and Map {|a|}") do N.times do |index| A.zip(B).map { |a| a.join } end end x.report("Zip and Map (&:)") do N.times do |index| A.zip(B).map(&:join) end end x.report("Transpose and Map (&:)") do N.times do |index| [A,B].transpose.map(&:join) end end end