该<=>
方法应分别返回“小于”、“等于”和“大于”的-1
或0
。1
对于某些类型的可排序对象,通常将排序顺序基于多个属性。以下工作,但我认为它看起来很笨拙:
class LeagueStats
attr_accessor :points, :goal_diff
def initialize pts, gd
@points = pts
@goal_diff = gd
end
def <=> other
compare_pts = points <=> other.points
return compare_pts unless compare_pts == 0
goal_diff <=> other.goal_diff
end
end
尝试一下:
[
LeagueStats.new( 10, 7 ),
LeagueStats.new( 10, 5 ),
LeagueStats.new( 9, 6 )
].sort
# => [
# #<LS @points=9, @goal_diff=6>,
# #<LS @points=10, @goal_diff=5>,
# #<LS @points=10, @goal_diff=7>
# ]
Perl 将0
其视为 false 值,这允许使用不同的语法进行复杂的比较:
{
return ( $self->points <=> $other->points ) ||
( $self->goal_diff <=> $other->goal_diff );
}
我发现通过操作符进行的直通0
操作||
简单易读且优雅。我喜欢使用||
的一件事是,一旦比较有值,计算就会短路。
我在 Ruby 中找不到类似的东西。有没有更好的方法来构建相同的比较复合体(或任何其他选择第一个非零项目),理想情况下不需要提前计算所有值?