Arborist::

HashUtilities

module

A collection of utilities for working with Hashes.

Public Instance Methods

anchor
compact_hash( hash )

Recursively remove hash pairs in place whose value is nil.

# File lib/arborist/mixins.rb, line 365
def compact_hash( hash )
        hash.each_key do |k|
                hash.delete( k ) if hash[ k ].nil?
                compact_hash( hash[k] ) if hash[k].is_a?( Hash )
        end
end
anchor
hash_matches( hash, key, val )

Returns true if the specified hash includes the specified key, and the value associated with the key either includes val if it is a Hash, or equals val if it's anything but a Hash.

# File lib/arborist/mixins.rb, line 376
def hash_matches( hash, key, val )
        actual = hash[ key ] or return false

        if actual.is_a?( Hash )
                if val.is_a?( Hash )
                        return val.all? {|subkey, subval| hash_matches(actual, subkey, subval) }
                else
                        return false
                end
        else
                return actual == val
        end
end
anchor
internify_keys( hash )
Alias for: symbolify_keys
anchor
merge_recursively( key, oldval, newval )

Recursive hash-merge function

# File lib/arborist/mixins.rb, line 340
def merge_recursively( key, oldval, newval )
        case oldval
        when Hash
                case newval
                when Hash
                        oldval.merge( newval, &method(:merge_recursively) )
                else
                        newval
                end

        when Array
                case newval
                when Array
                        oldval | newval
                else
                        newval
                end

        else
                newval
        end
end
anchor
stringify_keys( hash )

Return a version of the given hash with its keys transformed into Strings from whatever they were before.

# File lib/arborist/mixins.rb, line 304
def stringify_keys( hash )
        newhash = {}

        hash.each do |key,val|
                if val.is_a?( Hash )
                        newhash[ key.to_s ] = stringify_keys( val )
                else
                        newhash[ key.to_s ] = val
                end
        end

        return newhash
end
anchor
symbolify_keys( hash )

Return a duplicate of the given hash with its identifier-like keys transformed into symbols from whatever they were before.

# File lib/arborist/mixins.rb, line 321
def symbolify_keys( hash )
        newhash = {}

        hash.each do |key,val|
                keysym = key.to_s.dup.untaint.to_sym

                if val.is_a?( Hash )
                        newhash[ keysym ] = symbolify_keys( val )
                else
                        newhash[ keysym ] = val
                end
        end

        return newhash
end
Also aliased as: internify_keys