- 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 Nested Arrays
We have to #flatten the Array because the #sort uses <=> to compare two Arrays, which in turn, compares their elements for either all elements being less than all elements in the other Array or vice-versa (if neither condition is met they are considered equal). It doesn’t descend in to the Arrays to sort them. Here is what would happen if we didn’t flatten:
[[36, 25, 16], [9, 4, 1]].sort #=> [[9, 4, 1], [36, 25, 16]]
Once again, the first code will work in most cases but a recursive implementation is able to accommodate working with the Array in place without destroying the heirarchy (note that this sorts in place, for simplicity):
class Array def sort_recur! sort! do |a,b| a.sort_recur! if a.is_a? Array b.sort_recur! if b.is_a? Array a <=> b end end end p [[36, 25, 16], [9, 4, 1]].sort_recur!
Produces:
[[1, 4, 9], [16, 25, 36]]