Skip to content

Instantly share code, notes, and snippets.

@morika-t
Last active August 29, 2015 14:21
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save morika-t/e8170f315df4192a6b56 to your computer and use it in GitHub Desktop.
Save morika-t/e8170f315df4192a6b56 to your computer and use it in GitHub Desktop.
require 'active_support'
# in some cases i've found JSON.pretty_generate doesn't output properly
# when combined with ActiveSupport::OrderedHash without json/pure
# require 'json/pure'
def returning(value)
yield(value)
value
end
def convert_hash_to_ordered_hash_and_sort(object, deep = false)
# from http://seb.box.re/2010/1/15/deep-hash-ordering-with-ruby-1-8/
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
myhsh = {'x' => {3 => nil, 1 => nil, 5 => nil}, 'a' => {3 => nil, 1 => nil, 5 => nil}, 'a2' => {3 => nil, 1 => nil, 5 => nil}}
myhsh = convert_hash_to_ordered_hash_and_sort(myhsh, true)
puts JSON.pretty_generate(myhsh)
{
"a": {
"1": null,
"3": null,
"5": null
},
"a2": {
"1": null,
"3": null,
"5": null
},
"x": {
"1": null,
"3": null,
"5": null
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment