Comparable
In this page:
Comparable
Mixing in the Comparable module gives a class <, >, <=, >=, ==, and .between? automatically, as long as the class defines a single <=> ("spaceship") method that returns -1, 0, or 1. This is a good example of how a module can add a lot of functionality from a small amount of code you provide. It mirrors the role IComparable plays in some other languages.
Note: Implementing just <=> and including Comparable gets you six comparison operators plus .between? for free.
Example: Comparable
class Money
include Comparable
attr_reader :amount
def initialize(amount)
@amount = amount
end
def <=>(other)
amount <=> other.amount
end
end
a = Money.new(10)
b = Money.new(20)
puts a < b
puts a.between?(Money.new(5), Money.new(15))
Login to try C/C++/Java/PHP code in the editor
🔒
Chapter Quiz — Complete all 6 topics to unlock
0/6 topics done
Complete these topics first: