Sorting By Multiple Conditions in Ruby
Posted
by viatropos
on Stack Overflow
See other posts from Stack Overflow
or by viatropos
Published on 2010-04-13T23:53:18Z
Indexed on
2010/04/14
1:03 UTC
Read the original article
Hit count: 345
I have a collection of Post objects and I want to be able to sort them based on these conditions:
- First, by category (news, events, labs, portfolio, etc.)
- Then by date, if date, or by position, if a specific index was set for it
Some posts will have dates (news and events), others will have explicit positions (labs, and portfolio).
I want to be able to call posts.sort!
, so I've overridden <=>
, but am looking for the most effective way of sorting by these conditions. Below is a pseudo method:
def <=>(other)
# first, everything is sorted into
# smaller chunks by category
self.category <=> other.category
# then, per category, by date or position
if self.date and other.date
self.date <=> other.date
else
self.position <=> other.position
end
end
It seems like I'd have to actually sort two separate times, rather than cramming everything into that one method. Something like sort_by_category
, then sort!
. What is the most ruby way to do this?
© Stack Overflow or respective owner