4

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!

2
  • 1
    new_arr = arr.each_with_index.map {|value, index| value * index} Commented Jul 1, 2014 at 21:17
  • Wow, all I was missing was .map Commented Jul 1, 2014 at 21:24

3 Answers 3

6
[1, 2, 3, 4, 5].map.with_index(&:*)
Sign up to request clarification or add additional context in comments.

Comments

3

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

Comments

0

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 :)

2 Comments

That makes sense to me. Can you explain to me why new_arr = arr.each_with_index.map {|value, index| value * index} works but neither .each_with_index or .map_with_index work on their own? It seems weird to use .each_with_index.map.
The cool (and really important) thing about map is that it will return a new array at the end of the block. Map creates a new array where each will not. Furthermore, map will not work on this case by itself as it will not know what "index" is as map only iterates through the entire array. Each is not destructive nor will it return a new array.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.