# revised_gpa: version of gpa.rb that allows use as a library # In particular, this version can be run from the command # prompt by typing # ruby revised-gpa.rb # or can be loaded into another file to provide the # convert_to_numbers function as a utility to be used # in a larger project # string(ascii) -> array(float) # precondition: text is not empty def convert_to_numbers(text) letters = text.split(' ') numeric_values = letters.map do |c| if c == 'A' || c == 'a' 4.0 elsif c == 'B' || c == 'b' 3.0 elsif c == 'C' || c == 'c' 2.0 elsif c == 'D' || c == 'd' 1.0 else 0.0 # treat all others as F end end end def main puts "Enter grades (as A, B, C, etc.), entering a blank line to stop:" total = 0.0 count = 0 while ( (line = gets) && !line.chomp.empty? ) nums = convert_to_numbers line nums.each { |x| total += x } count += nums.length end if count == 0 puts "You must take classes to have a semester GPA!" end puts "Semester GPA: #{total / count}" end if __FILE__ == $0 main end