bdunagan

fill the void - bdunagan

23 Oct 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
Previous LinkedIn Twitter GitHub Email Next