Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
menu search
person
Welcome To Ask or Share your Answers For Others

Categories

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


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
379 views
Welcome To Ask or Share your Answers For Others

1 Answer

Try this:

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


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
...