0

First, I have found posts to sort values with possibles nil values, other posts to sort decending, but I didnet find the solution with both.

Here is where I am:

@records = @records.to_a.sort_by do |r| [-r.optimized_all_count, [r.year ? 1 : 0, r.year]] end

This works very well, but I want the "year" comparator to be descending. I tested this:

-[r.year ? 1 : 0, r.year]

but the sign "-" won't work with nil values. I also tried a.reverse...

How do obtain the year argument descending (and keeping -r.optimized_all_count as first sorting argument), ideally:

2020, 2018, 2017...nil, nil, nil.

Thanks

3
  • @records.to_a – is there by chance a database query involved? Commented Jan 11, 2021 at 15:21
  • 'to_a' is not required, and yes, it was an AR database query. Commented Jan 11, 2021 at 16:00
  • 2
    Did you consider delegating the sorting to the database? Commented Jan 11, 2021 at 18:07

2 Answers 2

1

Try this:

@records = @records.to_a.sort_by do |r| [-r.optimized_all_count, [r.year ? 0 : 1, r.year ? -r.year : nil]] end

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

Comments

1
@records.to_a.sort_by { |r| [-r.optimized_all_count, -(r.year || -Float::INFINITY)] }

It's not clear if .to_a is required.

1 Comment

'to_a' is not required in fact. Your solution is also working Cary, and shorter. Thanks.

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.