Chapter 10 - Comparable and Enumerable
Exercise 1: Comparing grades
We need a Ruby class to represent student letter grades from “A” through “F”. If you’re not familiar with the system, grades consist of the letters “A”, “B”, “C”, “D”, and “F”, with “A” being the best, and “F” being the worst.
The class will need letter
and letter=
accessor methods for the letter grade. The letter=
method should validate the letter being assigned, and raise an exception if it’s not “A”, “B”, “C”, “D”, or “F”. It should also include an initialize
method, so that we can pass a letter to Grade.new
and have it assigned to the letter
attribute.
We also need to be able to compare grades with the <
, >
, and ==
operators. An “A” grade should be considered “greater than” a “C” grade, an “F” grade should be “less than” a “D” grade, etc.
The above code outputs: