I want to specify a custom block method to sort an object array by evaluating two properties. However, after many searches, I didn\'t find to any example without the <=
-
This seems to work:
# Ascending
ar.sort! do |a,b|
(a-b).abs() > 0 ? a-b : 0
end
# Descending
ar.sort! do |a,b|
(a-b).abs() > 0 ? b-a : 0
end
There's no need for the spaceship operator ( <=>
) - it seems to be superfluous in Ruby (in terms of syntax efficiency), because Ruby considers 0
to be true, and for this usage specifically (above), you can just put the explicit 0
in the ternary operator.
- 热议问题