I'm doing prepwork for a course in which one of the challenges (which I failed, miserably) went something along the lines of:
Define a method that takes an array and multiplies each value in the array by its position in the array.
So basically, array = [1, 2, 3, 4, 5] should return 1*0, 2*1, 3*2, 4*3, 5*4.
I'm having a lot of trouble figuring out how to do it. I don't think they intended for us to use .inject or .reduce or anything but the bare basics.
This is what I've managed to do so far, but it doesn't run:
array = [1,2,3,4,5]
def calculator (arr)
new_arr = []
new_arr = arr.each_with_index {|value, index| value * index}
end
calculator(array)
I've tried some variations with .collect, and various parameters. Sometimes I get parameter errors or the array returned to me with nothing modified.
I would really appreciate an explanation or any advice!
new_arr = arr.each_with_index.map {|value, index| value * index}