Mapping values from two array in Ruby

放肆的年华 提交于 2019-12-02 20:26:52

@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 }
Curt Hagenlocher

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.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 has a map method (a.k.a. the collect method), which can be applied to any Enumerable object. If numbers is an array of numbers, the following line in Ruby:

numbers.map{|x| x + 5}

is the equivalent of the following line in Python:

map(lambda x: x + 5, numbers)

For more details, see here or here.

An alternative for the map that works for more than 2 arrays as well:

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}

This could also be added to 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 
标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!