Try the explanation:
You define an array
grades = [88,99,73,56,87,64]
and prepare a variable to store the amount:
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 at 0). That is why you must subtract 1 from the number of elements.
0.upto(grades.length - 1) do |loop_index|
Add the loop_index value to the amount.
sum += grades[loop_index] end
Now you are looping on each element and summing all the elements of the array.
You can calculate the average value:
average = sum/grades.length
Now you write the result to stdout:
puts average
It was a rude 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 a comment by Marc-Andres:
You can also use inject
to avoid determining the initial amount:
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