Sorting and something like the <=> operator

This is probably more of a Ruby question than a RoR question.

I need to sort an array of objects in descending order based on a
specific attribute. Sorting as follows results in an ascending order:

@items.sort! { |item1, item2|
item1.value_total <=> item2.value_total}

To order descending, I need to then:


I’m wondering if there is an operator similar to <=> that would result
in the reverse order? It seems a different operator could net a more
efficient algorithm. Or perhaps reverse is not an intensive activity?

Just flip it round :slight_smile:
@items.sort! { |item1, item2| item2.value_total <=> item1.value_total


Wow, for every good question I ask there are about three horrendous
ones. :slight_smile:

I had tried that earlier, but before I had fixed some other issues.
Got confused. Clearly that works.

This forum is not affiliated to the Ruby language, Ruby on Rails framework, nor any Ruby applications discussed here.

| Privacy Policy | Terms of Service | Remote Ruby Jobs