Class: Hash

Inherits:
Object show all
Defined in:
lib/utilrb/hash/slice.rb,
lib/utilrb/hash/map_key.rb,
lib/utilrb/hash/map_value.rb,
lib/utilrb/hash/to_sym_keys.rb,
lib/utilrb/hash/recursive_merge.rb

Instance Method Summary collapse

Instance Method Details

#map_keyObject

Creates a new hash for in which k => v has been mapped to yield(k, v) => v

See also #map_value


5
6
7
8
9
10
11
# File 'lib/utilrb/hash/map_key.rb', line 5

def map_key
    result = Hash.new
    each do |k, v|
        result[yield(k, v)] = v
    end
    result
end

#map_valueObject

Creates a new hash for in which k => v has been mapped to k => yield(k, v)

See also #map_key


5
6
7
8
9
10
11
# File 'lib/utilrb/hash/map_value.rb', line 5

def map_value
    result = Hash.new
    each do |k, v|
        result[k] = yield(k, v)
    end
    result
end

#recursive_merge(hash, &block) ⇒ Object


2
3
4
5
6
7
8
9
10
11
12
# File 'lib/utilrb/hash/recursive_merge.rb', line 2

def recursive_merge(hash, &block)
    merge(hash) do |k, v1, v2|
        if v1.kind_of?(Hash) && v2.kind_of?(Hash)
            v1.recursive_merge(v2, &block)
        elsif block_given?
            yield(k, v1, v2)
        else
            v2
        end
    end
end

#recursive_merge!(hash, &block) ⇒ Object


14
15
16
17
18
19
20
21
22
23
24
# File 'lib/utilrb/hash/recursive_merge.rb', line 14

def recursive_merge!(hash, &block)
    merge!(hash) do |k, v1, v2|
        if v1.kind_of?(Hash) && v2.kind_of?(Hash)
            v1.recursive_merge!(v2, &block)
        elsif block_given?
            yield(k, v1, v2)
        else
            v2
        end
    end
end

#slice(*keys) ⇒ Object


2
3
4
# File 'lib/utilrb/hash/slice.rb', line 2

def slice(*keys)
	keys.inject({}) { |h, k| h[k] = self[k] if has_key?(k); h }
end

#to_sym_keysObject

Returns a hash for which all keys have been converted to symbols (only valid for string/symbol keys of course)

{ 'a' => 1, :b => '2' }.to_sym_keys => { :a => 1, :b => '2' }

6
7
8
# File 'lib/utilrb/hash/to_sym_keys.rb', line 6

def to_sym_keys
	inject({}) { |h, (k, v)| h[k.to_sym] = v; h }
end