Lesson 9 of 10
Mixing modules into classes
- 13 min
- 6 checks
- 3 hints
- Go to task
Goal
Mixing in Comparable with include and <=>
Explanation
A module is a group of methods you don't create objects from. Instead, you mix it into classes: writing include Comparable inside a class adds the module's methods to it as if you had written them there yourself. That way, unrelated classes can share the same behavior without inheritance.
Comparable asks you for just one method, <=>, which returns a negative number if the object is smaller than the other one, zero if they're equal, and a positive number if it's larger. In return, it gives you <, >, ==, between? and clamp. sort and max rely on <=> too.
Take a real example: version numbers. If you compare them as strings, they're compared character by character, so "3.10.0" < "3.9.2" is true because the character "1" comes before "9", and max on the strings picks "3.9.2", not "3.10.0". So convert them to numbers first, because arrays compare element by element with <=>: [3, 10, 0] <=> [3, 9, 2] gives 1.
Your task
Define a Version class that is created from a string like Version.new("3.10.0"), mix Comparable into it, and define <=> to compare the parts of the version as numbers and to_s to return the string in the same format. Then set latest to the newest version in releases, as a Version object.
Checks
6 checks- Comparable is mixed into the Version class
- 3.10.0 is newer than 3.9.2 because the comparison uses numbers
- == comes from Comparable, and identical versions are equal
- between? checks that a version falls between two limits
- sort orders versions by number, and to_s returns the string
- latest is 3.10.0, not 3.9.2