在 Ruby 中迭代具有索引位置的数组

use*_*468 3 ruby arrays indexing methods

我正在为一门课程做准备工作,其中一个挑战(我惨败了)的内容如下:

定义一个方法,该方法采用数组并将数组中的每个值与其在数组中的位置相乘。

所以基本上, array = [1, 2, 3, 4, 5] 应该返回 1*0, 2*1, 3*2, 4*3, 5*4。

我很难弄清楚该怎么做。我不认为他们想让我们使用 .inject 或 .reduce 或除了最基本的东西之外的任何东西。

这是我到目前为止所做的,但它没有运行:

array = [1,2,3,4,5]

def calculator (arr)
new_arr = []
new_arr = arr.each_with_index {|value, index| value * index}
end

calculator(array)
Run Code Online (Sandbox Code Playgroud)

我尝试了 .collect 和各种参数的一些变体。有时我会遇到参数错误或数组返回给我而没有任何修改。

我真的很感激您的解释或任何建议!

saw*_*awa 6

[1, 2, 3, 4, 5].map.with_index(&:*)
Run Code Online (Sandbox Code Playgroud)