Misha Moroshko
Misha Moroshko

Reputation: 171351

Ruby: Is there a better way to write the following "sort" method?

Is there a nicer (and equivalent) way to sort items like this ?

 items.sort! do |p1, p2|
   if (p1.foo == p2.foo)
     if (p1.bar == p2.bar)
       if (p1.moo == p2.moo)
         p1.wow <=> p2.wow               # Ascending order
       else
         p2.sam.moo <=> p1.sam.moo       # Descending order, 2 levels attribute
       end
     else
       p2.bar <=> p1.bar                 # Descending order
     end
   else
     p1.foo <=> p2.foo                   # Ascending order
   end
 end

Upvotes: 1

Views: 142

Answers (1)

Nikita Rybak
Nikita Rybak

Reputation: 68006

You can turn objects in arrays for comparison

[p1.foo, p1.bar, p1.moo, p1.sam.moo] <=> [p2.foo, p2.bar, p2.moo, p2.sam.moo]

Arrays are compared just like strings: by the first differing element.

If inversed indexes in some comparisons (p2.bar <=> p1.bar) isn't a typo, you'll need to switch array elements too.

Or you can override comparison operator in your class

  def <=>(p2)
    ...
  end

In this case, you won't need to pass anything in items.sort!.

Upvotes: 3

Related Questions