Reputation: 45943
a = [3, 4, 7, 8, 3]
b = [5, 3, 6, 8, 3]
Assuming arrays of same length, is there a way to use each
or some other idiomatic way to get a result from each element of both arrays? Without using a counter?
For example, to get the product of each element: [15, 12, 42, 64, 9]
(0..a.count - 1).each do |i|
is so ugly...
Ruby 1.9.3
Upvotes: 5
Views: 113
Reputation: 59563
What about using Array.zip
:
>> a = [3,4,7,8,3]
=> [3, 4, 7, 8, 3]
>> b = [5,3,6,8,3]
=> [5, 3, 6, 8, 3]
>> c = []
=> []
>> a.zip(b) do |i, j| c << i * j end
=> [[3, 5], [4, 3], [7, 6], [8, 8], [3, 3]]
>> c
=> [15, 12, 42, 64, 9]
Note: I am very much not a Ruby programmer so I apologize for any idioms that I have trampled all over.
Upvotes: 6
Reputation: 168169
For performance reasons, zip
may be better, but transpose
keeps the symmetry and is easier to understand.
[a, b].transpose.map{|a, b| a * b}
# => [15, 12, 42, 64, 9]
A difference between zip
and transpose
is that in case the arrays do not have the same length, the former inserts nil
as a default whereas the latter raises an error. Depending on the situation, you might favor one over the other.
Upvotes: 4