-5

What is the meaning of '<==>' in Ruby?

Example: The code comes from the following class that compares numbers in the format x.x.x,

def <==>(other)
    # Some code here
end

The following code comes from this class that orders numbers like x.x.x,

class Version

    attr_reader :fst, :snd, :trd
    def initialize(version="")
        v = version.split(".")
        @fst = v[0].to_i
        @snd = v[1].to_i
        @trd = v[2].to_i
    end

    def <=>(other)
        return @fst <=> other.fst if ((@fst <=> other.fst) != 0)
        return @snd <=> other.snd if ((@snd <=> other.snd) != 0)
        return @trd <=> other.trd if ((@trd <=> other.trd) != 0)
    end

    def self.sort
        self.sort!{|a,b| a <=> b}
    end

    def to_s
        @sorted = @fst.to_s + "." + @snd.to_s + "." + @trd.to_s
        #Puts out "#{@sorted}".
    end
end
Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
user512568
  • 705
  • 1
  • 5
  • 4

2 Answers2

12

That is the spaceship operator. However, it is actually <=> (not <==>).

Although that is not its official name, I'm sure, it's the most commonly used name for that operator. It is a comparison operator where

  • If other is less than self, return 1,
  • If other is equal to self, return 0
  • If other is greater than self, return -1

It is a powerful operator in that by just implementing this you can do sorting of your own type and participate in a lot of other niceties, like the Enumerable mixin.

Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
Matt Greer
  • 60,826
  • 17
  • 123
  • 123
3

Why don't you just try it out? By just typing in the code you posted, it is trivial to see for yourself that it doesn't mean anything, since <==> is not a valid method name in Ruby. The code you posted will just raise a SyntaxError.

Jörg W Mittag
  • 363,080
  • 75
  • 446
  • 653