Class: Hash

Inherits:
Object show all
Defined in:
lib/utilities/hash.rb

Instance Method Summary collapse

Instance Method Details

#collect_keys(recursive = false, &block) ⇒ Object Also known as: map_keys

Returns a new hash with the results of running block once for every key in self



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

def collect_keys(recursive=false, &block)
  if block_given?
    each_with_object({}) do |(k,v),h|
      if recursive && v.kind_of?(Hash)
        h[yield(k)] = v.collect_keys(recursive, &block)
      else
        h[yield(k)] = v
      end
    end
  end
end

#collect_values(recursive = false, &block) ⇒ Object Also known as: map_values

Returns a new hash with the results of running block once for every value in self



17
18
19
20
21
22
23
24
25
26
27
# File 'lib/utilities/hash.rb', line 17

def collect_values(recursive=false, &block)
  if block_given?
    each_with_object({}) do |(k,v),h|
      if recursive && v.kind_of?(Hash)
        h[k] = v.collect_values(recursive, &block)
      else
        h[k] = yield(v)
      end
    end
  end
end

#stringify_keys(recursive = false) ⇒ Object

Returns a new hash where all keys have been stringified



36
37
38
# File 'lib/utilities/hash.rb', line 36

def stringify_keys(recursive=false)
  collect_keys(recursive){ |k| k.to_s }
end

#symbolize_keys(recursive = false) ⇒ Object

Returns a new hash where all keys have been symbolized



31
32
33
# File 'lib/utilities/hash.rb', line 31

def symbolize_keys(recursive=false)
  collect_keys(recursive){ |k| k.to_sym }
end