Deep Hash Ordering With Ruby 1.8 and 1.9

written by seb on January 15th, 2010 @ 01:19 PM

More like a memo than an article, I believe this piece of code that I made for i18n-js might be helpful.

UPDATE: Now also compatible with Ruby 1.9

def convert_hash_to_ordered_hash_and_sort(object, deep = false)
  if object.is_a?(Hash)
    # Hash is ordered in Ruby 1.9! 
    res = returning(RUBY_VERSION >= '1.9' ? Hash.new : ActiveSupport::OrderedHash.new) do |map|
      object.each {|k, v| map[k] = deep ? convert_hash_to_ordered_hash_and_sort(v, deep) : v }
    end
    return res.class[res.sort {|a, b| a[0].to_s <=> b[0].to_s } ]
  elsif deep && object.is_a?(Array)
    array = Array.new
    object.each_with_index {|v, i| array[i] = convert_hash_to_ordered_hash_and_sort(v, deep) }
    return array
  else
    return object
  end
end

Comments are closed