Home > Articles > Programming > Ruby

  • Print
  • + Share This
This chapter is from the book

This chapter is from the book

Sorting an Array

As long as all the objects stored in the Array respond to the <=> method, the Array will be sorted successfully. If you want to sort by some special criteria, you can supply a block or even map a value to each element that can be compared using “<=>”. Here is a somewhat contrived example (there are many ways to accomplish this):

['Platinum', 'Gold', 'Silver', 'Copper'].sort_by do
    case award
    when 'Platinum': 4
    when 'Gold': 3
    when 'Silver': 2
    when 'Copper': 1
    else 0
    #=> ["Copper", "Silver", "Gold", "Platinum"]

Above, a numerical value is assigned to each String and then the Array is sorted by #sort_by using those values.

Word of warning: When sorting numerical values, beware of Floats, they can have the value NaN (imaginary) which is, of course, not comparable to real numbers. Array#sort will fail if your array has such a NaN:

[1/0.0, 1, 0, -1, -1/0.0, (-1)**(0.5)]
    #=> [Infinity, 1, 0, -1, -Infinity, NaN]
[1/0.0, 1, 0, -1, -1/0.0, (-1)**(0.5)].sort


ArgumentError: comparison of Fixnum with Float
  • + Share This
  • 🔖 Save To Your Account