The <=>
method should return -1
, 0
or 1
for "less than", "equal to", and "greater than", respectively. For some types of sortable objects, it is normal to base the sort order on multiple properties. The following works, but I think it looks clumsy:
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
Trying it:
[
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 treats 0
as a false value, which allows complex comparisons with different syntax:
{
return ( $self->points <=> $other->points ) ||
( $self->goal_diff <=> $other->goal_diff );
}
I find the fall-through on 0
via the ||
operator simple to read and elegant. One thing I like about using ||
is the short-circuiting of calculations once the comparison has a value.
I cannot find anything similar in Ruby. Are there any nicer ways to build the same complex of comparisons (or anything else picking the first non-zero item), ideally without needing to calculate all values in advance?
In addition to sawa's answer, the result
can alsoshould be evaluated in-place, in order to return -1, 0 or +1:This works because of
Array#<=>
:After implementing
<=>
, you can includeComparable
and get<
,<=
,==
,>=
,>
andbetween?
for free.