-
-
Save sixtyfive/c5dbc32710e8b9f6f36fe00b30e31632 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
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