Sort objects by boolean values ​​in Ruby

My apologies if this was answered earlier or obvious ... did some searches here and in Goog and could not find the answer.

I am looking for sorting an array of suppliers by price and are they the preferred provider? (true or false)

For example, 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 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 the best ways to solve this problem?

+3
source share
2 answers

Most languages ​​provide sorting functions that comparators accept for these kinds of things. In Ruby, it's 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
       }
+7

<=> Provider, , , Array.sort ( Enumerable.sort_by). <=>, :

class Provider
  def <=>(other)
    if preferred_provider?
      if other.preferred_provider?
        @price <=> other.price
      else
        1
      end
    else
      if other.preferred_provider?
        -1
      else
        @price <=> other.price
      end
    end
  end
end

, p, p_sorted = p.sort.

( , , , , .)

+3

Source: https://habr.com/ru/post/1708985/


All Articles