Module: YamlNormalizer::Ext::SortByKey
- Defined in:
- lib/yaml_normalizer/ext/sort_by_key.rb
Overview
YamlNormalizer::Ext::SortByKey extends an instance of Hash to provide the additional public helper methods sort_by_key. The approach of extending Hash instances avoids monkey-patching a Ruby Core class and using refinements.
Instance Method Summary collapse
-
#sort_by_key(recursive: true) ⇒ Object
Sorts entries alphabetically by key and returns a new Hash.
Instance Method Details
#sort_by_key(recursive: true) ⇒ Object
Sorts entries alphabetically by key and returns a new Hash. sort_by_key does not modify the instance of Hash it’s called on.
19 20 21 22 23 24 |
# File 'lib/yaml_normalizer/ext/sort_by_key.rb', line 19 def sort_by_key(recursive: true) keys.sort_by(&:to_s).each_with_object({}) do |key, seed| value = seed[key] = fetch(key) seed[key] = value.extend(SortByKey).sort_by_key if recursive && value.instance_of?(Hash) end end |