ruby 将函数映射到多个数组

ruby map a function over multiple arrays

我有 2 个数组

   asc = [0, 1, 2, 3, 4, 5]
   dsc = [5, 4, 3, 2, 1, 0]

我想要一个新数组,它是将 asc 和 dsc 中的每个对应项相乘的结果

我习惯了 Clojure,我只是 map

(map #(* %1 %2) asc dsc) ;=> (0 4 6 6 4 0)

它们在 Ruby 中是否等效,在 Ruby 中执行此操作的惯用方法是什么?

我是 Ruby 的新手,但它似乎有非常简洁的解决方案,所以我想我遗漏了什么。

我只写:

i = 0
res = []

while i < asc.length() do
  res.append(asc[i] * dsc[i])
end

使用zip将每个元素与其对应的元素组合在两个元素数组中,然后映射

asc.zip(dsc).map { |a, b| a * b }
 => [0, 4, 6, 6, 4, 0] 

使用map and with_index:

asc = [0, 1, 2, 3, 4, 5]
dsc = [5, 4, 3, 2, 1, 0]
res = asc.map.with_index{ |el, i| el * dsc[i] }
puts res.inspect
# [0, 4, 6, 6, 4, 0]

或者,使用 each_index and map:

res = asc.each_index.map{ |i| asc[i] * dsc[i] }

似乎 dsc(“降序”)派生自 asc(“升序”),在这种情况下,您可以这样写:

asc.each_index.map { |i| asc[i] * asc[-i-1] } 
  #=> [0, 4, 6, 6, 4, 0]

你也可以这样写:

[asc, dsc].transpose.map { |a,d| a*d }
  #=> [0, 4, 6, 6, 4, 0]

或:

require 'matrix'

Matrix[asc].hadamard_product(Matrix[dsc]).to_a.first
  #=> [0, 4, 6, 6, 4, 0]

参见 Matrix#hadamard_product

你也可以这样写:

asc = [0, 1, 2, 3, 4, 5]
dsc = [5, 4, 3, 2, 1, 0]

p asc.zip(dsc).collect{|z| z.inject(:*)}
[0, 4, 6, 6, 4, 0]