Solution: Calculate Average Score by Reading a File

Go over the implementation for calculating the average of the integer scores read from a text file.

Solution

Press + to interact
main.rb
score1.txt
score2.txt
score3.txt
score4.txt
score5.txt
def cal_avg_score(file_name)
file_content = File.read(file_name)
array = []
file_content.split("\n").each do |line|
array << line.to_i
end
the_average = 0
the_sum = array.inject{|sum,x| sum + x }
the_average = the_sum * 1.0 / array.size if the_sum
the_average = the_average.round(1) if the_average
return the_average
end
  • ...

Get hands-on with 1400+ tech skills courses.