Class: Hash
- Inherits:
-
Object
- Object
- Hash
- Defined in:
- lib/immosquare-extensions/hash.rb
Overview
##
This extension adds utility methods to the Hash class. It includes methods for handling and manipulating the keys and values of a hash in various ways.
##
Instance Method Summary collapse
-
#depth ⇒ Object
## Calculate the depth (or level) of nesting within a hash.
-
#downcase_key ⇒ Object
## Convert all keys of the hash to lowercase.
-
#flatten_hash ⇒ Object
## Flatten a nested hash into a single-level hash.
-
#sort_by_key(recursive = false, &block) ⇒ Object
## Sort a hash by its keys.
-
#without(*keys) ⇒ Object
## Remove multiple keys from a hash in a single command.
Instance Method Details
#depth ⇒ Object
##
Calculate the depth (or level) of nesting within a hash.
Example: {b: {c: 1}}.depth => 3
##
44 45 46 |
# File 'lib/immosquare-extensions/hash.rb', line 44 def depth 1 + values.map {|v| v.is_a?(Hash) ? v.depth : 1 }.max end |
#downcase_key ⇒ Object
##
Convert all keys of the hash to lowercase. If a value is an array, it recursively processes the nested hash elements.
Example: { “A” => { “B” => “value” } }.downcase_key => “a”=>{“b”=>“value”}
##
31 32 33 34 35 36 |
# File 'lib/immosquare-extensions/hash.rb', line 31 def downcase_key keys.each do |k| store(k.downcase, (v = delete(k)).is_a?(Array) ? v.map(&:downcase_key) : v) end self end |
#flatten_hash ⇒ Object
##
Flatten a nested hash into a single-level hash. Nested keys are represented with dot notation.
Reference: stackoverflow.com/questions/23521230/flattening-nested-hash-to-a-single-hash-with-ruby-rails
Example: {b: {c: 1}}.flatten_hash => Hash.:a:a.b:a.b.c=>1
##
75 76 77 78 79 80 81 82 83 84 85 |
# File 'lib/immosquare-extensions/hash.rb', line 75 def flatten_hash each_with_object({}) do |(k, v), h| if v.is_a?(Hash) v.flatten_hash.map do |h_k, h_v| h["#{k}.#{h_k}".to_sym] = h_v end else h[k] = v end end end |
#sort_by_key(recursive = false, &block) ⇒ Object
##
Sort a hash by its keys. If the recursive flag is true, it will sort nested hashes as well.
Reference: dan.doezema.com/2012/04/recursively-sort-ruby-hash-by-key/
Example: 1, a: {d: 4, c: 3}.sort_by_key(true) => :d=>4, :b=>1}
##
58 59 60 61 62 63 |
# File 'lib/immosquare-extensions/hash.rb', line 58 def sort_by_key(recursive = false, &block) keys.sort(&block).each_with_object({}) do |key, seed| seed[key] = self[key] seed[key] = seed[key].sort_by_key(true, &block) if recursive && seed[key].is_a?(Hash) end end |
#without(*keys) ⇒ Object
##
Remove multiple keys from a hash in a single command.
Reference: apidock.com/ruby/Hash/delete
Examples: 1, b: 2, c: 3.without(:a, :b) => :c=>3
##
17 18 19 20 21 |
# File 'lib/immosquare-extensions/hash.rb', line 17 def without(*keys) cpy = dup keys.each {|key| cpy.delete(key) } cpy end |