Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is there an idiomatic way to operate on 2 arrays in Ruby?

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

like image 369
B Seven Avatar asked Oct 19 '12 02:10

B Seven


2 Answers

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.

like image 185
D.Shawley Avatar answered Oct 31 '22 08:10

D.Shawley


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.

like image 39
sawa Avatar answered Oct 31 '22 08:10

sawa