I want to know what is the meaning of def <=>(other) in ruby methods. I want to know what is the <=> in ruby method.
Asked
Active
Viewed 113 times
3
Boris Stitnicky
- 12,444
- 5
- 57
- 74
2 Answers
2
<=> is not "in" Ruby method, #<=> is a Ruby method. This method is used for comparable objects (members of ordered sets) to easily gain implementation of #<, #>, #== etc. methods by including Comparable mixin.
class GradeInFiveLevelScale
include Comparable
attr_reader :grade
def initialize grade; @grade = grade end
def <=> other; other.grade <=> grade end
def to_s; grade.to_s end
end
a = GradeInFiveLevelScale.new 1
b = GradeInFiveLevelScale.new 1
c = GradeInFiveLevelScale.new 3
a > b #=> false
a >= b #=> true
a > c #=> true
Boris Stitnicky
- 12,444
- 5
- 57
- 74