3

I want to know what is the meaning of def <=>(other) in ruby methods. I want to know what is the <=> in ruby method.

Boris Stitnicky
  • 12,444
  • 5
  • 57
  • 74

2 Answers2

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
2

<=> is the combined comparison operator. It returns 0 if first operand equals second, 1 if first operand is greater than the second and -1 if first operand is less than the second.

More info on this SO thread.

Community
  • 1
  • 1
Simon
  • 619
  • 2
  • 9
  • 23