在Ruby中映射来自两个数组的值

我想知道在Ruby中是否有办法用Python做我可以做的事情:

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

我有两个相同大小的数组与权重和数据,但我似乎无法找到类似于Ruby中的map的函数,减少我的工作。

@Michiel de Mare

您的Ruby 1.9示例可以进一步缩短:

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

另请注意,在Ruby 1.8中,如果需要ActiveSupport(来自Rails),您可以使用:

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

在Ruby 1.9中:

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

在Ruby 1.8中:

 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方法(也就是collect方法),它可以应用于任何Enumerable对象。 如果numbersnumbers数组,则Ruby中的以下行:

 numbers.map{|x| x + 5} 

相当于Python中的以下行:

 map(lambda x: x + 5, numbers) 

有关详细信息,请参阅此处或此处 。

地图的替代方案也适用于2个以上的数组:

 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} 

这也可以添加到Array:

 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