### 从Ruby中的两个数组映射值

``````sum = reduce(lambda x, y: x + y, map(lambda x, y: x * y, weights, data))
``````

#### 6 个答案:

@Michiel de Mare

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

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

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

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

Array.zip函数执行元素的元素组合。它不像Python语法那么干净，但是这里有一种方法可以使用：

``````weights = [1, 2, 3]
data = [4, 5, 6]
result = Array.new
a.zip(b) { |x, y| result << x * y } # For just the one operation

sum = 0
a.zip(b) { |x, y| sum += x * y } # For both operations
``````

Ruby有`map`方法（a.k.a。`collect`方法），可以应用于任何`Enumerable`对象。如果`numbers`是数字数组，则Ruby中的以下行：

``````numbers.map{|x| x + 5}
``````

``````map(lambda x: x + 5, numbers)
``````

``````def dot(*arrays)
arrays.transpose.map {|vals| yield vals}
end

dot(weights,data) {|a,b| a*b}

# OR, if you have a third array

dot(weights,data,offsets) {|a,b,c| (a*b)+c}
``````

``````class Array
def dot
self.transpose.map{|vals| yield vals}
end
end

[weights,data].dot {|a,b| a*b}

#OR

[weights,data,offsets].dot {|a,b,c| (a*b)+c}
``````

``````weights = [1,2,3]
data    = [10,50,30]

require 'matrix'
Vector[*weights].inner_product Vector[*data] # => 200
``````