sort_by with Boolean in Rails

19,127

Solution 1

You could cheat and get it to return a number:

sort_by { |a| a.thing ? 0 : 1 }

Solution 2

You could use partition and then flatten the results:

partition{|v| v == true}.flatten

Solution 3

By using ActiveRecord's order (included in Rails):

collection.order(thing: :desc)

Solution 4

Since there are a couple different ways represented here, I went ahead and benchmarked them to see which is fastest, sorting 27,000 items based upon a boolean attribute:

Rehearsal ---------------------------------------------
sort_by     0.070000   0.000000   0.070000 (  0.075203)
partition   0.110000   0.000000   0.110000 (  0.114667)
order       0.000000   0.000000   0.000000 (  0.000046)
------------------------------------ total: 0.180000sec

            user     system      total        real
sort_by     0.010000   0.000000   0.010000 (  0.016611)
partition   0.110000   0.000000   0.110000 (  0.111384)
order       0.000000   0.000000   0.000000 (  0.000047)

So yes, keeping things on the SQL side definitely makes things faster.

Share:
19,127
AdamNYC
Author by

AdamNYC

Updated on June 02, 2022

Comments

  • AdamNYC
    AdamNYC about 2 years

    I know that boolean in Ruby are classes. But from practical point of view, is there a way to sort an array by boolean (i.e., with all elements with true value first)?

    Thank you.