-
-
Save apeiros/cb4cab4f1d5075b06c08d43ba63c3ad1 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
ClassOrder = Hash.new(0).merge(Array => 1, Hash => 2) | |
def recursive_sort(obj, &sorter) | |
case obj | |
when Hash | |
obj.map { |k,v| [k, recursive_sort(v, &sorter)] }.sort(&sorter).to_h | |
when Array | |
obj.map { |v| recursive_sort(v, &sorter) }.sort(&sorter) | |
else | |
obj | |
end | |
end | |
demo = {'b'=>['2',{},[],'1','3'],'c'=>{}, 'a'=>'10'} | |
recursive_sort(demo) { |a,b| | |
if a.class == b.class | |
a <=> b | |
else | |
ClassOrder[a.class] <=> ClassOrder[b.class] | |
end | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment