如何将数组中的数字乘以其在数组中的位置,然后将 ruby 中的数组的总和相加?我不明白如何在 map 函数中访问数组的索引
例如:我怎样才能让 [5, 7, 13, 2] 去 [5*0, 7*1, 13*2, 2*3] 然后得到这个数组的总和。
IE
def array_method (numbers)
numbers.map{|i| i* ?????}
end
array_method([5, 7, 13, 2])
这也不起作用,它返回一个空数组,我不知道我做错了什么。
[5,7,13,2].map.with_index(&:*).inject(:+)
# => 39
Array如果您希望该方法可用于所有数组,您可以修改该类:
class Array
def sum_with_index
self.map.with_index { |element, index| element * index }.inject(:+)
end
end
控制台输出
2.0.0-p247 :001 > [5, 7, 13, 2].sum_with_index
=> 39
[5,7,13,2].each_with_index.map{|value,index|value*index}.reduce{|a,b|a+b}
def array_method (numbers)
ans = 0
numbers.each_with_index {| num, idx | ans += (idx) * num }
end
使用注入
def dot_product_with_index(array)
(0..array.count-1).inject(0) {|r,i| r + array[i]*i}
end