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!
[1, 2, 3, 4, 5].map.with_index(&:*)
If you wanted something super basic:
def calculator (array)
count = 0
new_array = []
array.each do |number|
new_array<<number*count
count +=1
end
return new_array
end
It's not the most "clean" way but does help you walk through the problem :)
To me best and easiest way is:
result = [1, 2, 3, 4, 5].each_with_index.map {|value, index| value * index}
Which results in:
[0, 2, 6, 12, 20]
Or in another way without using map
you can do:
[1, 2, 3, 4, 5].each_with_index do |value, index|
puts value * index
end
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.