Search code examples
rubyiteratorruby-1.9.3enumerable

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


Solution

  • 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.