Class: Hash

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

Overview

Instance Method Summary collapse

Instance Method Details

#recurse(*types) {|h| ... } ⇒ Object

Apply a block to hash, and recursively apply that block to each sub-hash or types.

h = {:a=>1, :b=>{:b1=>1, :b2=>2}}
g = h.recurse{|h| h.inject({}){|h,(k,v)| h[k.to_s] = v; h} }
g  #=> {"a"=>1, "b"=>{"b1"=>1, "b2"=>2}}

Yields:

  • (h)


11
12
13
14
15
16
17
18
19
20
21
22
23
# File 'lib/endeca_on_demand/core_ext/hash.rb', line 11

def recurse(*types, &block)
  types = [self.class] if types.empty?
  h = inject({}) do |hash, (key, value)|
    case value
    when *types
      hash[key] = value.recurse(*types, &block)
    else
      hash[key] = value
    end
    hash
  end
  yield h
end

#recurse!(&block) ⇒ Object

In place form of #recurse.



26
27
28
# File 'lib/endeca_on_demand/core_ext/hash.rb', line 26

def recurse!(&block)
  replace(recurse(&block))
end