Reputation: 1635
Hello I have the following two arrays in ruby
A=["a","b","c"]
B=["d","e","f"]
and I want to produce this
C = ["ad", "be", "cf"]
regardless of array length. The two arrays are always the same length though.
Is there a neat way to do this? I mean instead of iterating through the arrays with a for loop.
Upvotes: 2
Views: 1559
Reputation: 4860
Just for the record, a benchmark with the different listed solutions. Results:
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)
Benchmark
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
Upvotes: 2
Reputation: 7978
As an alternative to zip
, you can use transpose
which raises an exception if the two arrays aren't the same cardinality.
[A,B].transpose.map(&:join)
Upvotes: 2
Reputation: 118261
Very simple with the method Array#zip
and Array#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"]
One more way ( but not looks good ), :-)
A.map.with_index { |e,i| e + B[i] }
# => ["ad", "be", "cf"]
Upvotes: 6