标签: spacecraft-operator

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

这是我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)

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

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

ruby mixins spacecraft-operator

9
推荐指数
1
解决办法
199
查看次数

在Ruby中按多个条件排序

我有一组Post对象,我希望能够根据这些条件对它们进行排序:

  • 首先,按类别(新闻,事件,实验室,投资组合等)
  • 然后按日期,如果是日期,或按位置,是否为其设置了特定索引

一些帖子将有日期(新闻和事件),其他帖子将有明确的职位(实验室和投资组合).

我希望能够打电话posts.sort!,所以我已经覆盖了<=>,但我正在寻找最有效的排序方式.以下是伪方法:

def <=>(other)
  # first, everything is sorted into 
  # smaller chunks by category
  self.category <=> other.category

  # then, per category, by date or position
  if self.date and other.date
    self.date <=> other.date
  else
    self.position <=> other.position
  end
end
Run Code Online (Sandbox Code Playgroud)

看起来我必须实际排序两次,而不是将所有内容都塞进那个方法中.那样的sort_by_categorysort!.最红宝石的方法是什么?

ruby sorting operators comparison-operators spacecraft-operator

8
推荐指数
1
解决办法
5561
查看次数