Sha256: 84a203155d9147b8c7dca0ed45fb4609babe5a7c017d9cb66775b3d76225b495

Contents?: true

Size: 1.65 KB

Versions: 21

Compression:

Stored size: 1.65 KB

Contents

# frozen_string_literal: true

module Doing
  # Hash helpers
  class ::Hash
    ##
    ## Freeze all values in a hash
    ##
    ## @return     { description_of_the_return_value }
    ##
    def deep_freeze
      map { |k, v| v.is_a?(Hash) ? v.deep_freeze : v.freeze }.freeze
    end

    def deep_freeze!
      replace deep_freeze
    end

    # Turn all keys into string
    #
    # Return a copy of the hash where all its keys are strings
    def stringify_keys
      each_with_object({}) { |(k, v), hsh| hsh[k.to_s] = v.is_a?(Hash) ? v.stringify_keys : v }
    end

    # Turn all keys into symbols
    def symbolize_keys
      each_with_object({}) { |(k, v), hsh| hsh[k.to_sym] = v.is_a?(Hash) ? v.symbolize_keys : v }
    end

    # Set a nested hash value using an array
    #
    # @example `{}.deep_set(['one', 'two'], 'value')`
    # @example `=> { 'one' => { 'two' => 'value' } }
    #
    # @param      path   [Array] key path
    # @param      value  The value
    #
    def deep_set(path, value)
      if path.count == 1
        if value
          self[path[0]] = value
        else
          delete(path[0])
        end
      else
        if value
          self.default_proc = ->(h, k) { h[k] = Hash.new(&h.default_proc) }
          dig(*path[0..-2])[path.fetch(-1)] = value
        else
          return self unless dig(*path)

          dig(*path[0..-2]).delete(path.fetch(-1))
          path.pop
          cleaned = self
          path.each do |key|
            if cleaned[key].empty?
              cleaned.delete(key)
              break
            end
            cleaned = cleaned[key]
          end
          empty? ? nil : self
        end
      end
    end
  end
end

Version data entries

21 entries across 21 versions & 1 rubygems

Version Path
doing-2.1.19 lib/doing/hash.rb
doing-2.1.18 lib/doing/hash.rb
doing-2.1.17 lib/doing/hash.rb
doing-2.1.16 lib/doing/hash.rb
doing-2.1.15 lib/doing/hash.rb
doing-2.1.14 lib/doing/hash.rb
doing-2.1.13 lib/doing/hash.rb
doing-2.1.12 lib/doing/hash.rb
doing-2.1.11 lib/doing/hash.rb
doing-2.1.10 lib/doing/hash.rb
doing-2.1.9 lib/doing/hash.rb
doing-2.1.8 lib/doing/hash.rb
doing-2.1.7 lib/doing/hash.rb
doing-2.1.6 lib/doing/hash.rb
doing-2.1.6pre lib/doing/hash.rb
doing-2.1.5pre lib/doing/hash.rb
doing-2.1.4pre lib/doing/hash.rb
doing-2.1.3 lib/doing/hash.rb
doing-2.1.2pre lib/doing/hash.rb
doing-2.1.1pre lib/doing/hash.rb