Sha256: 4c759e9ba76d9b58f2329433b4c17e39d6ec5eb404225f33dcf70461d1fa0595
Contents?: true
Size: 1.1 KB
Versions: 21
Compression:
Stored size: 1.1 KB
Contents
# frozen_string_literal: true require 'active_support/core_ext/array/wrap' class Hash # Returns a flat hash where all nested keys are collapsed into a an array of keys. # # hash = { person: { name: { first: 'Rob' }, age: '28' } } # hash.flatten_keys # => {[:person, :name, :first]=>"Rob", [:person, :age]=>"28"} # hash # => { person: { name: { first: 'Rob' }, age: '28' } } def flatten_keys _flatten_keys(self) end # Replaces current hash with a flat hash where all nested keys are collapsed into a an array of keys. # Returns +nil+ if no changes were made, otherwise returns the hash. # # hash = { person: { name: { first: 'Rob' }, age: '28' } } # hash.flatten_keys! # => {[:person, :name, :first]=>"Rob", [:person, :age]=>"28"} # hash # => {[:person, :name, :first]=>"Rob", [:person, :age]=>"28"} def flatten_keys! replace(_flatten_keys(self)) end private def _flatten_keys(h, keys = [], res = {}) return res.merge!(keys => h) unless h.is_a? Hash h.each { |k, r| _flatten_keys(r, keys + Array.wrap(k), res) } res end end
Version data entries
21 entries across 21 versions & 1 rubygems