Last active
August 29, 2015 14:21
-
-
Save morika-t/e8170f315df4192a6b56 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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) |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
{ | |
"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