In Ruby, the
mixin of Comparable is used by the class whose objects may be ordered. The class must be defined using an operator which compare the receiver against another object. It will return
-1, 0, and 1 depending upon the receiver. If the receiver is less than another object, then it returns -1, if the receiver is equal to another object, then it returns 0. If the receiver is greater than another object, then it returns 1. Comparable module use <=> to implement the conventional comparison operators(<, <=, ==, >=, and >) and the method
between?
Example:
Output:
true
true
false
Instance Method
- < : It compares two objects based on the receiver's method and return true if it return -1 otherwise return false.
obj<other_obj
- <= : It compares two objects based on the receiver's method and return true if it return -1 or 0 otherwise return false.
obj<=other_obj
- == : It compares two objects based on the receiver's method and return true if it return 0 otherwise return false.
obj==other_obj
- > : It compares two objects based on the receiver's method and return true if it return 1 otherwise return false.
obj>other_obj
- >= : It compares two objects based on the receiver's method and return true if it return 1 or 0 otherwise return false.
obj>=other_obj
Example:
Output:
true
true
false
false
false
between? : This method returns false if the obj <=> min is less than or if obj <=> max is greater than zero. Otherwise, it returns true.
obj.between?(min, max)
Example:
Output:
false
true
Reference: https://ruby-doc.org/core-2.2.0/Comparable.html