Ruby - 使用 Comparable mixin 比较两个不同属性的对象
有没有一种简单的方法(即使用 spaceship 运算符)来定义 Ruby 中基于两个不同属性的比较?即,如果我有一个包含两个属性(attr1 和 attr2)的类,是否有一种 Rubyesque 方法可以在 attr1 上比较该类的两个实例,如果它们相等,则在 attr2 上比较它们?
Is there an easy way (i.e. using the spaceship operator) to define comparison in Ruby based on two different attributes? I.e. If I have a class that contains two attributes, attr1 and attr2, is there a Rubyesque way of comparing two instances of this class on attr1, and if they're equal then compare them on attr2?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
这是一种易于扩展(扩展到更多属性)的方式:
This is an easily extendible (to more attributes) way:
可比较 mixin 的全部目的是为宇宙飞船(比较)运算符提供定义。因此,如果您想对两个属性进行比较,那就这样做吧。这是一个过于冗长的示例:
显然,上面假设
attr1
和attr2
都有太空船运算符的定义。此外,您还需要确定什么构成大于和小于,这对于两个属性来说可能有点困难。这表明可比较的代码可能不适合您的场景。A more succinct and idiomatic way of writing this would be:
The whole point of the comparable mixin is to provide a definition for the spaceship (comparison) operator. So if you want to do a comparison across two attributes, then do it. Here's an overly verbose example:
Obviously the above assumes
attr1
, andattr2
both have definitions for the spaceship operator. As well you'll need to determine what constitutes greater than, and less than, which is likely a bit difficult across two attributes. Which suggests that comparable may not be the proper code for your scenario.A more succinct and idiomatic way of writing this would be:
太空飞船具有“不可比较”
太空飞船要求:
Steenslag 的解决方案是当“不可比较”时,不要给我零。
实施
添加了额外的行来应对“不可比较”:
Spaceship with 'not comparable'
Spaceship requires:
Steenslag's solution wasn't giving me the nil when 'not comparable'.
Impementation
Added extra line for coping with 'not comparable':