Billjk Billjk - 5 months ago 14
Ruby Question

upto method in Ruby

I'm learning ruby, and there has been a bit of talk about the

upto
method in the book from which I am learning. What exactly does it do, I'm confused...
Example:

grades = [88,99,73,56,87,64]
sum = 0
0.upto(grades.length - 1) do |loop_index|
sum += grades[loop_index]
end
average = sum/grades.length
puts average

Answer

Let's try an explanation:

You define an array

grades = [88,99,73,56,87,64]

and prepare a variable to store the sum:

sum = 0

grades.length is 6 (there are 6 elements in the array), (grades.length - 1) is 5.

with 0.upto(5) you loop from 0 to 5, loop_index will be 0, then 1...

The first element of the array is grades[0] (the index in the array starts with 0). That's why you have to subtract 1 from the number of elements.

0.upto(grades.length - 1) do |loop_index|

Add the loop_index's value to sum.

    sum += grades[loop_index]
end

Now you looped on each element and have the sum of all elements of the array.

You can calculate the average:

average = sum/grades.length

Now you write the result to stdout:

puts average

This was a non-ruby-like syntax. Ruby-like you would do it like this:

grades = [88,99,73,56,87,64]
sum = 0
grades.each do |value|
    sum += value
end
average = sum/grades.length
puts average

Addendum based on Marc-Andrés comment:

You may use also inject to avoid to define the initial sum:

grades = [88,99,73,56,87,64] 
sum = grades.inject do |sum, value|     
  sum + value 
end
average = sum / grades.length 
puts average 

Or even shorter:

grades = [88,99,73,56,87,64] 
average = grades.inject(:+) / grades.length 
puts average