Skip to content

Instantly share code, notes, and snippets.

@sixtyfive
Last active February 3, 2023 14:06
Show Gist options
  • Save sixtyfive/c5dbc32710e8b9f6f36fe00b30e31632 to your computer and use it in GitHub Desktop.
Save sixtyfive/c5dbc32710e8b9f6f36fe00b30e31632 to your computer and use it in GitHub Desktop.
module CoreExtensions
module Hash
module AdvancedManipulations
# adapted from http://dan.doezema.com/2012/04/recursively-sort-ruby-hash-by-key/
def recursively_sort_by_key(&block)
self.keys.sort(&block).reduce({}) do |seed,key|
seed[key] = self[key]
if seed[key].is_a?(Hash)
# why does it never get here?
seed[key] = seed[key].recursively_sort_by_key(&block)
end
seed
end
end
end
end
end
Hash.include CoreExtensions::Hash::AdvancedManipulations
h = {peter: {lisa: 1, mary: 2, anja: 4, frank: 3}, klaus: 0}
pp h.recursively_sort_by_key # keys are not sorted because #is_a?(Hash) above never became true...
# it checks _sub_classes, not _immediate_ classes, alright, but where
# is there any subclassing going on here?
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment