Search⌘ K
AI Features

Solution: Grades Histogram

Explore how to build a grades histogram in Ruby by reading data from a file, converting it to integers, and counting values within defined ranges. Understand the use of arrays, loops, and hashes to solve this file handling and data processing problem effectively.

We'll cover the following...

Solution

Ruby 3.1.2
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 ...