.sum method not working?

Ok so in this challenge, were given this array. We have to multiply each number by its respective index position.

Then take each of the products and add them all together for the final answer.

I got each of the products, but i cant figure out why the .sum method isn’t working to add all the products.

First, the .sum method works perfectly fine on the original array. I even removed the brackets before and it still worked fine.

Second, the do statement works fine and my code isnt broken

In the pic, as soon as i call the .sum method on product i get this nomethoderror. When CLEARLY .sum is a method bc i just used it a min ago on the “numbers” array

When you do product.sum, you’re calling the .sum method onto a SINGLE integer. The .sum method works with arrays. How line 29-34 loop works is that product is created by multiplying the index * the specific number, which solves part of your assignment. But when it loops again, it is just reassigning that single number to the next index’s product.

Ok i think i understand…one thing though, the product variable, its not a single integer tho its a series of numbers as per this image. So even though its not contained in brackets the .sum method should still work on the product variable as it would on an array, no?

Your do loop iterates over the numbers array one number at a time. So the product variable inside the do loop is a number, not an array of numbers, which is why it doesn’t have a sum method.

(1..5).collect.each_with_index { |n, i| n * i }.sum

Here we iterate over the range to make an array with collect, and we iterate over that with each_with_index which passes the array item and the index to the block. The block multiplies them together for each array entry and returns the array of products, which gets accumulated by the sum method.


This exactly. To piggyback a bit. What the console shows isn’t always exactly what you should expect Ruby to interpret. What is showing in Atom is Product being printed. Then Product updating its single value to another value. Then Product being printed again. [1, 2, 3, 4, 5].sum works perfectly, whereas 1.sum doesn’t work.

1 Like

Ohhh i see now, the .sum is applied to one integer at a time due to the do method. Which makes no sense logically…got it thank you guys so much for your help!!

1 Like

This forum is not affiliated to the Ruby language, Ruby on Rails framework, nor any Ruby applications discussed here.

| Privacy Policy | Terms of Service | Remote Ruby Jobs