Comparable
Comparable teaches a class how to compare its objects, giving it bigger and smaller checks for free. It is like showing kids how to line up by height.
In this page:
Syntax
class ClassName
include Comparable
def <=>(other)
attribute <=> other.attribute
end
end
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
Related Topics
{# common_mistakes/chapter_summary/browser_support: on Hindi pages the
view already swaps in the hi_ translation fields (or blanks these
out if untranslated), so this renders correctly for both languages
without a lang_code check here. #}
Common Mistakes
- Including
Comparablewithout defining<=>, so<and>raise errors. - Returning
trueorfalsefrom<=>, when it must return-1,0,1(ornil). - Comparing with an object of another type in
<=>, which raises an error whenother.amountis missing.
🔒
Chapter Quiz — Complete all 6 topics to unlock
0/6 topics done
Complete these topics first: