Comparing plain old Ruby objects

Try Google-ing for <=> it not very helpful. It’s the spaceship method, I can never remember that. So in my case I had a custom classes representing a remote resource and I needed to compare if these objects were similar based on their id. If you compare object == other_object, they won’t be the same because they are different objects in memory. You could write…

class Tentacle
  def ==(other)
    self.id == other.id
  end
end

..but what about >, >=, <, <=, !=, etc. Comparable covers all of this.

class Tentacle
  include Comparable
  def <=>(other)
    self.id <=> other.id
  end
end

…but what if the object you’re comparing against is an instance of another class?

class Tentacle
  def <=>(other)
    return nil unless other.is_a?(self.class)
    self.id <=> other.id
  end
end

And that was the day that was.