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开发者_JAVA技巧
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?)
Yep just include Comparable
- the only requirement is to have the spaceship <=>
method defined.
精彩评论