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

Posted by jeremy Ruten on Stack Overflow See other posts from Stack Overflow or by jeremy Ruten
Published on 2010-05-12T02:54:13Z Indexed on 2010/05/12 3:04 UTC
Read the original article Hit count: 296

Filed under:
|

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?)

© Stack Overflow or respective owner

Related posts about ruby

Related posts about mixin