bdunagan

Brian Dunagan

October 23 2011
Ruby Tip: Sort a hash recursively

A while ago, I found a great Stackoverflow answer for sorting a hash in Ruby:

class Hash
  def sorted_hash(&block)
    self.class[sort(&block)]
  end
end

But recently, I wanted to take it a bit further and recursively sort all the hashes in an object, even if they are inside of an array. Here is a snippet to do that:

class Hash
  def sorted_hash(&block)
    self.class[
      self.each do |k,v| 
        self[k] = v.sorted_hash(&block) if v.class == Hash
        self[k] = v.collect {|a| a.sorted_hash(&block)} if v.class == Array
      end.sort(&block)]
  end
end
Ruby Tip: 1.8.7 and 1.9.2, Side by Side Server Tip: Screen
LinkedIn GitHub Email