重写 Ruby 的宇宙飞船运算符 <=>
我正在尝试覆盖 Ruby 的 <=> (宇宙飞船)操作员对苹果和橙子进行排序,首先按重量排序苹果,然后按甜度排序橙子。就像这样:
module Fruity
attr_accessor :weight, :sweetness
def <=>(other)
# use Array#<=> to compare the attributes
[self.weight, self.sweetness] <=> [other.weight, other.sweetness]
end
include Comparable
end
class Apple
include Fruity
def initialize(w)
self.weight = w
end
end
class Orange
include Fruity
def initialize(s)
self.sweetness = s
end
end
fruits = [Apple.new(2),Orange.new(4),Apple.new(6),Orange.new(9),Apple.new(1),Orange.new(22)]
p fruits
#should work?
p fruits.sort
但这不起作用,有人能告诉我我在这里做错了什么,或者有更好的方法吗?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
您的问题是您只初始化了两侧的一个属性,另一个属性仍然是
nil
。Array#<=>
方法中不会处理nil
,这最终会终止排序。有几种方法可以首先解决这个问题,例如
nil.to_i
为您提供0
,这将使此工作正常进行。Your problem is you are only initializing one of the properties on either side, the other one will still be
nil
.nil
isn't handled in theArray#<=>
method, which ends up killing the sort.There are a few ways to handle the problem first would be something like this
nil.to_i
gives you0
, which will let this work.不过,可能晚了...
添加以下 Monkeypatch
并更改
Fruity::<=> 的主体至
Probably late, nevertheless...
add the following monkeypatch
And change the body of
Fruity::<=> to