Search code examples
ruby-on-railsrubysortingbooleanenumerable

Sort Objects by Boolean values in Ruby


My apologies if this has been answered before or is obvious...did some searching here and on the Goog and couldn't find an answer.

I'm looking to sort an array of Providers by price and whether they are a preferred_provider? (true or false)

For instance in array p of Providers...

p1.price == 1, p1.preferred_provider? == false
p2.price == 2, p2.preferred_provider? == true
p2.price == 3, p3.preferred_provider? == true

I would like to p.sort_by and get:

[p2 p3 p1]

IAW

p.sort_by {|x| x.preferred_provider?, x.price }

does not work and gets...

undefined method `<=>' for false:FalseClass

Any suggestions on better ways to approach this problem?


Solution

  • Most languages provide sort functions that accept comparators for this sort of thing. In Ruby, this is just array.sort:

    p.sort {|a, b| if (a.preferred_provider? == b.preferred_provider?
                   then a.price <=> b.price
                   elsif a.preferred_provider?
                        1
                   else -1
           }