Class: Hash

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

Instance Method Summary collapse

Instance Method Details

#compactObject

{ 4=>35, 9=>nil, 10=>false }.compact #=> 10=>false

{ 4=>35, 9=>nil, 10=>false }.compact(&:blank?)  #=> {4=>35}


8
9
10
# File 'lib/lxa_core_extensions/hash.rb', line 8

def compact
  reject { |k,v| block_given? ? yield(v) : v.nil? }
end

#flipObject

make a new hash with the existing values as the new keys

  • like #rassoc for each existing key

  • like invert but with all keys as array

    3=>4, 5=>6, 6=>2, 7=>4.flip #=> 6], 4=>[3, 7], 6=>



18
19
20
# File 'lib/lxa_core_extensions/hash.rb', line 18

def flip
  build_hash { |h,(k,v)| h[v] ||= []; h[v] << k }
end

#nested_keys(&block) ⇒ Object

return all the keys of all the sub hashes



38
39
40
41
42
43
44
45
# File 'lib/lxa_core_extensions/hash.rb', line 38

def nested_keys(&block)
  Enumerator.new do |y|
    to_a.each do |k,v|
      y.yield k
      v.nested_keys { |nk| y.yield(nk) } if v.is_a?(Hash)
    end
  end.each(&block)
end

#rekey(&block) ⇒ Object

change all the keys of the has by yielding it to the supplied block, recursively

{1=>2, 3=>4, 5=>{6=>7, 8=>9}}.rekey(&:to_s) #=> {"1"=>2,"3"=>4, "5"=>{"6"=>7, "8"=>9}}


27
28
29
30
31
32
33
34
# File 'lib/lxa_core_extensions/hash.rb', line 27

def rekey(&block)
  build_hash do |h,(k,v)|
    new_key = yield(k)
    new_val = v.is_a?(Hash) ? v.rekey(&block) : v

    h[new_key] = new_val
  end
end

#to_ostructObject



48
49
50
# File 'lib/lxa_core_extensions/hash.rb', line 48

def to_ostruct
  OpenStruct.new(self)
end