Home > Articles > Programming > Ruby

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

This chapter is from the book

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

p [[36, 25, 16], [9, 4, 1]].sort_recur!


[[1, 4, 9], [16, 25, 36]]
  • + Share This
  • 🔖 Save To Your Account