January 2024
Intermediate to advanced
718 pages
20h 15m
English
If you want to be able to compare two objects of the same class in general, all you need to do is implement the <=> operator and include the Comparable module:
| | class Team |
| | include Comparable |
| | attr_accessor :wins, :losses, :name |
| | |
| | def initialize(name, wins, losses) |
| | @name = name |
| | @wins = wins |
| | @losses = losses |
| | end |
| | |
| | def percentage = (wins * 1.0) / (wins + losses) |
| | |
| | def <=>(other) |
| | raise ArgumentError unless other.is_a?(Team) |
| | percentage <=> other.percentage |
| | end |
| | |
| | def to_s = name |
| | end |
| | |
| | brewers = Team.new("Brewers", 73, 89) |
| | cardinals = Team.new("Cardinals", 86, 76) |
| | cubs = Team.new("Cubs", 103, 58) |
| | pirates = Team.new("Pirates", 78, 83) ... |
Read now
Unlock full access