...

/

Solution: Grades Histogram

Solution: Grades Histogram

Look at the solution for generating the grades histogram.

We'll cover the following...

Solution

Press + to interact
main.rb
grades.txt
nums = []
grades_file = File.expand_path File.join(File.dirname(__FILE__), "grades.txt")
grades_content = File.read(grades_file)
grades_content.split.each do |num|
nums << num.to_i
end
range_array = []
min_number = 0
max_number = 100
(0..max_number).step(10).each do |num|
next if min_number == num
if num == max_number
range_array << { :min => min_number, :max => num, :count => 0} # initialise
else
range_array << { :min => min_number, :max => num-1, :count => 0} # initialise
end
min_number = num
end
range_array.each do |entry|
nums.each do |x|
if x >= entry[:min] && x <= entry[:max]
entry[:count] += 1
end
end
puts "#{entry[:min].to_s.rjust(2)} - #{entry[:max].to_s.rjust(3)}: #{"*" * entry[:count]}"
end

Explanation

  • Line 1: An empty nums array is created to hold grade values.

  • Lines 3–7: The program reads the ...