- Slicing an Array
- Iterating over an Array
- Creating Enumerable Classes
- Sorting an Array
- Iterating over Nested Arrays
- Modifying All the Values in an Array
- Sorting Nested Arrays
- Building a Hash from a Config File
- Sorting a Hash by Key or Value
- Eliminating Duplicate Data from Arrays (Sets)
- Working with Nested Sets
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 |award| case award when 'Platinum': 4 when 'Gold': 3 when 'Silver': 2 when 'Copper': 1 else 0 end end #=> ["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
Produces:
ArgumentError: comparison of Fixnum with Float failed