Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Can you define <=> in Ruby and then have ==, >, <, >=, and <= defined automatically?

Here's part of my Note class:

class Note
  attr_accessor :semitones, :letter, :accidental

  def initialize(semitones, letter, accidental = :n)
    @semitones, @letter, @accidental = semitones, letter, accidental
  end

  def <=>(other)
    @semitones <=> other.semitones
  end

  def ==(other)
    @semitones == other.semitones
  end

  def >(other)
    @semitones > other.semitones
  end

  def <(other)
    @semitones < other.semitones
  end
end

It seems to me like there should be a module that I could include that could give me my equality and comparison operators based on my <=> method. Is there one?

I'm guessing a lot of people run into this kind of problem. How do you usually solve it? (How do you make it DRY?)

like image 595
Paige Ruten Avatar asked May 12 '10 02:05

Paige Ruten


1 Answers

Yep just include Comparable - the only requirement is to have the spaceship <=> method defined.

like image 92
Jakub Hampl Avatar answered Sep 24 '22 23:09

Jakub Hampl