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:
class Geeksforgeeks
include Comparable
attr :name
def <=>(other_name)
name.length <=> other_name.name.length
end
def initialize(name)
@name = name
end
end
a1 = Geeksforgeeks. new ( "G" )
a2 = Geeksforgeeks. new ([ 3 , 5 ])
a3 = Geeksforgeeks. new ( "geeks" )
p a1 < a2
p a2.between?(a1, a3)
p a3.between?(a1, a2)
|
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:
class Geeksforgeeks
include Comparable
attr :name
def <=>(other_name)
name.length <=> other_name.name.length
end
def initialize(name)
@name = name
end
end
a1 = Geeksforgeeks. new ( "G" )
a2 = Geeksforgeeks. new ( "geeks" )
p a1 < a2
p a1 <= a2
p a1 == a2
p a1 >= a2
p a1 > a2
|
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:
p 7 .between?( 2 , 6 )
p 'geeks' .between?( 'geeks' , 'gfg' )
|
Output:
false
true
Reference: https://ruby-doc.org/core-2.2.0/Comparable.html
Last Updated :
10 Oct, 2018
Like Article
Save Article
Share your thoughts in the comments
Please Login to comment...