Mapping values from two array in Ruby Mapping values from two array in Ruby ruby ruby

Mapping values from two array in Ruby


@Michiel de Mare

Your Ruby 1.9 example can be shortened a bit further:

weights.zip(data).map(:*).reduce(:+)

Also note that in Ruby 1.8, if you require ActiveSupport (from Rails) you can use:

weights.zip(data).map(&:*).reduce(&:+)


In Ruby 1.9:

weights.zip(data).map{|a,b| a*b}.reduce(:+)

In Ruby 1.8:

weights.zip(data).inject(0) {|sum,(w,d)| sum + w*d }


The Array.zip function does an elementwise combination of arrays. It's not quite as clean as the Python syntax, but here's one approach you could use:

weights = [1, 2, 3]data = [4, 5, 6]result = Array.newa.zip(b) { |x, y| result << x * y } # For just the one operationsum = 0a.zip(b) { |x, y| sum += x * y } # For both operations