Search⌘ K
AI Features

Solution: Calculate Average

Explore how to calculate averages in Ruby through practical examples using arrays and the inject method. Understand counting, summing, and looping techniques to handle composite data types effectively in your programs.

Courtney's version

array = []
count = 0
puts "Enter scores: " 
while true
    input = gets.chomp.to_i 
    if input == -1
        break 
    else
        array << input
        count += 1 
    end
end
sum = 0
array.each do |number|
    sum += number 
end
average = sum / count
puts "Average score: #{average}"
Calculating the average using a loop

Explanation

  • Line 10: The count of values is maintained by incrementing count ...