maps - Mappatura dei valori da due array in Ruby

original title: "maps - Mapping values from two array in Ruby"


I'm wondering if there's a way to do what I can do below with Python, in Ruby:

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

I have two arrays of equal sizes with the weights and data but I can't seem to find a function similar to map in Ruby, reduce I have working.

Mi chiedo se c'è un modo per fare quello che posso fare di seguito con Python, in Ruby: sum = reduce (lambda x, y: x + y, map (lambda x, y: x * y, pesi, dati)) Ho due matrici di dimensioni uguali con il ...

Questo è il riepilogo dopo la traduzione, se è necessario visualizzare la traduzione completa, fare clic sull'icona "traduci"

Tutte le risposte
  • Translate

    @Michiel de Mare

    Your Ruby 1.9 example can be shortened a bit further:*).reduce(:+)

    Also note that in Ruby 1.8, if you require ActiveSupport (from Rails) you can use:*).reduce(&:+)

  • Translate

    In Ruby 1.9:{|a,b| a*b}.reduce(:+)

    In Ruby 1.8: {|sum,(w,d)| sum + w*d }

  • Translate

    The 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 = { |x, y| result << x * y } # For just the one operation
    sum = 0 { |x, y| sum += x * y } # For both operations

  • Translate

    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:{|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.

  • Translate

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

    def dot(*arrays) {|vals| yield vals}
    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{|vals| yield vals}
    [weights,data].dot {|a,b| a*b}
    [weights,data,offsets].dot {|a,b,c| (a*b)+c}

  • Translate
    weights = [1,2,3]
    data    = [10,50,30]
    require 'matrix'
    Vector[*weights].inner_product Vector[*data] # => 200