Sha256: 39c64da51ff8e5360746734fcaa2e1943fc201bc527f80f7082285060143a768

Contents?: true

Size: 637 Bytes

Versions: 2

Compression:

Stored size: 637 Bytes

Contents

class Hash

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

  # In place form of #recurse.
  def recurse!(&block)
    replace(recurse(&block))
  end

end

Version data entries

2 entries across 2 versions & 1 rubygems

Version Path
facets-2.9.0.pre.2 lib/core/facets/hash/recurse.rb
facets-2.9.0.pre.1 lib/core/facets/hash/recurse.rb