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

时间:2014-03-10 22:17:20

标签: ruby arrays merge

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

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

我想制作这个

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

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

有一种巧妙的方法吗?我的意思是不是用for循环迭代数组。

3 个答案:

答案 0 :(得分:5)

方法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"]

答案 1 :(得分:1)

作为zip的替代方案,您可以使用transpose,如果两个数组的基数不同,则会引发异常。

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

答案 2 :(得分:1)

仅供记录,使用不同的列出解决方案的基准。结果:

                              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