Skip to content

Instantly share code, notes, and snippets.

@codeitagile
Last active March 15, 2016 13:47
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 codeitagile/ec4f2b9f0756d534c6c5 to your computer and use it in GitHub Desktop.
Save codeitagile/ec4f2b9f0756d534c6c5 to your computer and use it in GitHub Desktop.
Deep sorting hashes that contain array values adapted from https://gist.github.com/trevor/1083930
# Adapted from https://gist.github.com/trevor/1083930
def returning(value)
yield(value)
value
end
def convert_hash_to_ordered_hash_and_sort(object, deep = false)
if object.is_a?(Hash)
res = returning({}) 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 = []
object.each_with_index { |v, i| array[i] = convert_hash_to_ordered_hash_and_sort(v, deep) }
return array.sort
else
return object
end
end
def output_report(f, results)
f.puts YAML.dump(convert_hash_to_ordered_hash_and_sort(results, true))
end
@codeitagile
Copy link
Author

The output_report part is clearly specific to my use case.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment