'Ruby's times method and for loop does the same thing, but what are the respective processes?

I have a paradigm where the purpose is to calculate "the total accumulated from 'variable from' to 'variable to'". I got two methods, but I don't know exactly what steps they go through.

The first is the times method. I don't understand what (to - from +1) produces and why (i + from)? Also, this code throws syntax error, unexpected end, expecting end-of-input, I don't know where I am going wrong .

from = 10
to = 20
sum = 0
  (to - from +1).times to |i|
    sum = sum + (i + from)
  end
puts sum

Then there is the for loop. I can't understand what is the "total sum accumulated from 'variable from' to 'variable to'", what is the process of adding it?

from = 10
to = 20
sum = 0
for i in from..to
  sum = sum + i
end
puts sum

I'm bad at math, thank you all.



Solution 1:[1]

Here are a few idiomatic ways of solving this problem in Ruby. They might be a little easier to follow than the solution you proposed.

sum = 0

10.upto(20) do |i|
  sum = sum + i
end

For the first iteration of loop, i will = 10, the second, i will = 11 and so "up to" 20. Each time it will add the value of i to sum. When it completes, sum will have a value of 165.

Another way is this:

10.upto(20).sum

The reason this works is that 10.upto(20) returns an Enumerator. You can call sum on an Enumerator.

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Dharman