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
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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With