这是我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)
在我看来,应该有一个我可以包含的模块,可以根据我的<=>
方法给我我的相等和比较运算符.有吗?
我猜很多人遇到这种问题.你通常如何解决它?(你怎么让它干?)
我有一组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_category
话sort!
.最红宝石的方法是什么?
ruby sorting operators comparison-operators spacecraft-operator