Module: Collapsium::RecursiveSort
Overview
Provides recursive sort functions for hashes.
Constant Summary
Constants included from ViralCapabilities
ViralCapabilities::DEFAULT_ANCESTORS, ViralCapabilities::ENHANCED_MARKER, ViralCapabilities::READ_METHODS, ViralCapabilities::WRITE_METHODS
Constants included from Support::Methods
Support::Methods::BUILTINS, Support::Methods::WRAPPER_HASH
Instance Method Summary collapse
-
#recursive_sort(&block) ⇒ Object
Same as #recursive_sort!, but returns a copy.
-
#recursive_sort!(&block) ⇒ Object
Recursively sort a Hash by its keys.
Methods included from ViralCapabilities
call_virality, copy_mods, enhance, enhance_array_value, enhance_hash_value, enhance_value, extended, extended, included, included, prepended, prepended, set_ancestors
Methods included from Support::Methods
builtins, loop_detected?, repeated, #resolve_helpers, #wrap_method, wrappers
Instance Method Details
#recursive_sort(&block) ⇒ Object
Same as #recursive_sort!, but returns a copy.
52 53 54 55 56 57 58 59 60 |
# File 'lib/collapsium/recursive_sort.rb', line 52 def recursive_sort(&block) ret = nil if respond_to?(:recursive_dup) ret = recursive_dup else ret = dup end return ret.recursive_sort!(&block) end |
#recursive_sort!(&block) ⇒ Object
Recursively sort a Hash by its keys. Without a block, this function will not be able to compare keys of different size.
24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 |
# File 'lib/collapsium/recursive_sort.rb', line 24 def recursive_sort!(&block) # If we have IndifferentAccess, we need to sort keys appropriately. the_keys = nil if singleton_class.ancestors.include?(IndifferentAccess) the_keys = IndifferentAccess.sorted_keys(keys, &block) else the_keys = keys.sort(&block) end return the_keys.reduce(self) do |seed, key| # Delete (and later re-insert) value for ordering value = self[key] delete(key) # Recurse into Hash values if value.is_a?(Hash) value.recursive_sort!(&block) end # re-insert value self[key] = value next seed end end |