# gpa: compute gpa based on semester grades - assumes each class same # number of credits # 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 puts "Enter grades (as A, B, C, etc.), entering a blank line or end-of-file to stop:" total = 0.0 count = 0 while ( (line = gets) && !line.chomp.empty? ) nums = convert_to_numbers line # the following statement is equivalent to # i = 0; while i < nums.length; total += nums[i]; i += 1; end 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}"