Sign Up

Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.

Have an account? Sign In

Have an account? Sign In Now

Sign In

Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.

Sign Up Here

Forgot Password?

Don't have account, Sign Up Here

Forgot Password

Lost your password? Please enter your email address. You will receive a link and will create a new password via email.

Have an account? Sign In Now

You must login to ask a question.

Forgot Password?

Need An Account, Sign Up Here

Please briefly explain why you feel this question should be reported.

Please briefly explain why you feel this answer should be reported.

Please briefly explain why you feel this user should be reported.

Sign InSign Up

The Archive Base

The Archive Base Logo The Archive Base Logo

The Archive Base Navigation

  • SEARCH
  • Home
  • About Us
  • Blog
  • Contact Us
Search
Ask A Question

Mobile menu

Close
Ask a Question
  • Home
  • Add group
  • Groups page
  • Feed
  • User Profile
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Buy Points
  • Users
  • Help
  • Buy Theme
  • SEARCH
Home/ Questions/Q 720721
In Process

The Archive Base Latest Questions

Editorial Team
  • 0
Editorial Team
Asked: May 14, 20262026-05-14T05:47:28+00:00 2026-05-14T05:47:28+00:00

I have a collection of Post objects and I want to be able to

  • 0

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?

  • 1 1 Answer
  • 0 Views
  • 0 Followers
  • 0
Share
  • Facebook
  • Report

Leave an answer
Cancel reply

You must login to add an answer.

Forgot Password?

Need An Account, Sign Up Here

1 Answer

  • Voted
  • Oldest
  • Recent
  • Random
  1. Editorial Team
    Editorial Team
    2026-05-14T05:47:29+00:00Added an answer on May 14, 2026 at 5:47 am

    You should always sort by the same criteria to insure a meaningful order. If comparing two nil dates, it is fine that the position will judge of the order, but if comparing one nil date with a set date, you have to decide which goes first, irrespective of the position (for example by mapping nil to a day way in the past).

    Otherwise imagine the following:

    a.date = nil                   ; a.position = 1
    b.date = Time.now - 1.day      ; b.position = 2
    c.date = Time.now              ; c.position = 0
    

    By your original criteria, you would have: a < b < c < a. So, which one is the smallest??

    You also want to do the sort at once. For your <=> implementation, use #nonzero?:

    def <=>(other)
      return nil unless other.is_a?(Post)
      (self.category <=> other.category).nonzero? ||
      ((self.date || AGES_AGO) <=> (other.date || AGES_AGO)).nonzero? ||
      (self.position <=> other.position).nonzero? ||
      0
    end
    

    If you use your comparison criteria just once, or if that criteria is not universal and thus don’t want to define <=>, you could use sort with a block:

    post_ary.sort{|a, b| (a.category <=> ...).non_zero? || ... }
    

    Better still, there is sort_by and sort_by! which you can use to build an array for what to compare in which priority:

    post_ary.sort_by{|a| [a.category, a.date || AGES_AGO, a.position] }
    

    Besides being shorter, using sort_by has the advantage that you can only obtain a well ordered criteria.

    Notes:

    • sort_by! was introduced in Ruby 1.9.2. You can require 'backports/1.9.2/array/sort_by' to use it with older Rubies.
    • I’m assuming that Post is not a subclass of ActiveRecord::Base (in which case you’d want the sort to be done by the db server).
    • 0
    • Reply
    • Share
      Share
      • Share on Facebook
      • Share on Twitter
      • Share on LinkedIn
      • Share on WhatsApp
      • Report

Sidebar

Related Questions

I have the following code: // // POST: /PlayRoundHole/Create [AcceptVerbs(HttpVerbs.Post)] public ActionResult Create(FormCollection collection)
I have Class and Student objects. Both have collection of another as property. Which
I have some points that I need to classify. Given the collection of these
I have a complex view model which contains a collection of other objects which
I have an app and I am able to post to a user's wall
I have a collection of std::set . I want to find the intersection of
I have a custom object that implements INotifyPropertyChanged. I have a collection of these
I have the following POST request: POST http://blah/Request HTTP/1.1 Host: blah Content-Length: 322 Proxy-Connection:
I have Collection List<Car> . How to compare each item from this collection with
Lets say I have collection of documents with specified longitude and latitude. type is

Explore

  • Home
  • Add group
  • Groups page
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Users
  • Help
  • SEARCH

Footer

© 2021 The Archive Base. All Rights Reserved
With Love by The Archive Base

Insert/edit link

Enter the destination URL

Or link to existing content

    No search term specified. Showing recent items. Search or use up and down arrow keys to select an item.