user2257812
user2257812

Reputation:

What does <=> method do?

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

Upvotes: 2

Views: 125

Answers (2)

Boris Stitnicky
Boris Stitnicky

Reputation: 12578

<=> 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

Upvotes: 1

Simon
Simon

Reputation: 629

<=> 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.

Upvotes: 2

Related Questions