你能在Ruby中定义<=>然后自动定义==,>,<,> =和<=吗?

Jer*_*ten 9 ruby mixins spacecraft-operator

这是我Note班级的一部分:

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
Run Code Online (Sandbox Code Playgroud)

在我看来,应该有一个我可以包含的模块,可以根据我的<=>方法给我我的相等和比较运算符.有吗?

我猜很多人遇到这种问题.你通常如何解决它?(你怎么让它干?)

Jak*_*mpl 13

是的include Comparable- 唯一的要求是<=>定义宇宙飞船方法.