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

Version Path
activeset-0.6.5 lib/patches/core_ext/hash/flatten_keys.rb
activeset-0.6.4 lib/patches/core_ext/hash/flatten_keys.rb
activeset-0.6.3 lib/patches/core_ext/hash/flatten_keys.rb
activeset-0.6.2 lib/patches/core_ext/hash/flatten_keys.rb
activeset-0.6.1 lib/patches/core_ext/hash/flatten_keys.rb
activeset-0.6.0 lib/patches/core_ext/hash/flatten_keys.rb
activeset-0.5.8 lib/patches/core_ext/hash/flatten_keys.rb
activeset-0.5.7 lib/patches/core_ext/hash/flatten_keys.rb
activeset-0.5.6 lib/patches/core_ext/hash/flatten_keys.rb
activeset-0.5.5 lib/patches/core_ext/hash/flatten_keys.rb
activeset-0.5.4 lib/patches/core_ext/hash/flatten_keys.rb
activeset-0.5.3 lib/patches/core_ext/hash/flatten_keys.rb
activeset-0.5.2 lib/patches/core_ext/hash/flatten_keys.rb
activeset-0.5.1 lib/patches/core_ext/hash/flatten_keys.rb
activeset-0.5.0 lib/patches/core_ext/hash/flatten_keys.rb
activeset-0.4.4 lib/patches/core_ext/hash/flatten_keys.rb
activeset-0.4.3 lib/patches/core_ext/hash/flatten_keys.rb
activeset-0.4.2 lib/patches/core_ext/hash/flatten_keys.rb
activeset-0.4.1 lib/patches/core_ext/hash/flatten_keys.rb
activeset-0.4.0 lib/patches/core_ext/hash/flatten_keys.rb