- Trending Categories
- Data Structure
- Operating System
- C Programming
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
Comparable module in Ruby
In Ruby, the class whose objects can be ordered uses the Comparable mixin. Class definitions need to include an operator to compare receivers with each other. The operator will return either -1, 0, or 1.
It returns -1 if the receiver is less than another object.
If it is greater than another object, then it returns 1.
It returns 0 if the receiver is equal to another object.
In the Comparable module, the operator <=> is used to implement the conventional comparison operators (*, <=, ==, >=, and >) and sometimes also between? method as well.
Now that we know a little about the comparable module in Ruby, let's explore a few examples on the same.
Consider the code shown below
class TutorialsPoint # comparable module include Comparable attr :key def <=>(other_key) key.length <=> other_key.key.length end def initialize(key) @key = key end end # creating objects a1 = TutorialsPoint.new("T") a2 = TutorialsPoint.new([3, 6]) a3 = TutorialsPoint.new("tuts") # comparable operator puts a1 < a2 # using between? method puts a2.between?(a1, a3) puts a3.between?(a1, a2)
true true false
In the above example, we used only one operator for comparison; there are 5 more such operators available to us.
Consider the code shown below that depicts the use of all these comparison operators.
class TutorialsPoint # comparable module include Comparable attr :key def <=>(other_key) key.length <=> other_key.key.length end def initialize(key) @key = key end end # creating objects a1 = TutorialsPoint.new("T") a2 = TutorialsPoint.new([3, 6]) a3 = TutorialsPoint.new("tuts") # comparable operators puts a1 < a2 puts a1 <= a2 puts a1 == a2 puts a1 >= a2 puts a1 > a2
true true false false false
- Comparable vs Comparator in Java
- Difference between Comparable and Comparator in Java
- Lambda Functions in Ruby
- Python vs Ruby
- Static Members in Ruby Programming
- Yield keyword in Ruby Programming
- Transpose() function in Ruby Programming
- Range class methods in Ruby
- Types of iterators in Ruby
- Array shift function in Ruby
- Array slice function in Ruby
- Control flow alterations in Ruby
- Connecting SAP in Ruby on Rails
- How to use BigDecimal in Ruby?
- How to freeze objects in Ruby?