2

In the following piece of code, due_date and position are optional fields, whereas important is a field which is always set to either true or false.

posts.sort_by do |post| 
  [post.due_date || 0, post.position || 0, post.important? ? 0 : 1]
end

I'm trying to figure out how multiple sort works. If due_date is present, then it takes precedence or sets it to zero. Why are we something setting it to zero here?

3
  • 2
    If you sort_by a collection words by word.length it compares word lengths. If you compare arrays, IIRC it walks the array until there's something !=, e.g., if the due_date isn't equal, that's the comparison. If it is, it's position, etc. You set something to zero as a way of providing a default value if there's nothing in that field. Commented Feb 28, 2014 at 21:04
  • arrays sort by the natural ordering of the first element; if there is a tie, those ties are sorted by the second element; etc. Commented Feb 28, 2014 at 21:05
  • Refer to this answer, that's not exactly your problem, but the solution may be of some help. Commented Feb 28, 2014 at 21:28

1 Answer 1

1

The problem here is nothing particularly about multiple comparison. If you compare arrays, each of the elements will be compared to the corresponding one in another array. If those values sometimes take numerical values, then they always have to be numerals. Numerals cannot be compared to nil, and doing so will raise an error. Defaulting them to zero is to ensure they are numerals. As long as you default them to a numeral, it will not raise an error. The particular choice of zero was based on where you want to position the entries with the missing values; you could have chosen infinity, negative infinity, etc for different results.

Sign up to request clarification or add additional context in comments.

4 Comments

how should I handle datetime fields in that case. I cannot default them to zero or Time.now
You can create a dummy Time object with the Unix epoch.
How do I create that object, and what value would it be equal to.
Time.new(0). It would be smaller than any other time object.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.