Sha256: 496e0c0f2667e5aae2ea4878a9d09cf1d7f113ed8450ad2d19e3208f26118e5e

Contents?: true

Size: 1.11 KB

Versions: 7

Compression:

Stored size: 1.11 KB

Contents

class Hash

  # Returns a new hash created by traversing the hash and its subhashes,
  # executing the given block on the key and value. The block should
  # return a 2-element array of the form +[key, value]+.
  #
  #   h = { "A"=>"A", "B"=>"B" }
  #   g = h.traverse { |k,v| [k.downcase, v] }
  #   g  #=> { "a"=>"A", "b"=>"B" }
  #
  # TODO: Contrast these to recursibely --we may not need both.
  #
  # TODO: Testing value to see if it is a Hash also catches subclasses of Hash.
  #       This is probably not the right thing to do and should catch Hashes only (?)
  #
  #  CREDIT: Trans

  def traverse(&b)
    inject({}) do |h,(k,v)|
      v = ( Hash === v ? v.traverse(&b) : v )
      nk, nv = b[k,v]
      h[nk] = nv #( Hash === v ? v.traverse(base,&b) : nv )
      h
    end
  end

  # In place version of traverse, which traverses the hash and its
  # subhashes, executing the given block on the key and value.
  #
  #   h = { "A"=>"A", "B"=>"B" }
  #   h.traverse! { |k,v| [k.downcase, v] }
  #   h  #=> { "a"=>"A", "b"=>"B" }
  #
  #  CREDIT: Trans

  def traverse!(&b)
    self.replace( self.traverse(&b) )
  end

end

Version data entries

7 entries across 7 versions & 2 rubygems

Version Path
facets-2.4.0 lib/facets/hash/traverse.rb
facets-2.4.1 lib/facets/hash/traverse.rb
facets-2.4.2 lib/core/facets/hash/traverse.rb
facets-2.4.3 lib/core/facets/hash/traverse.rb
facets-2.4.4 lib/core/facets/hash/traverse.rb
facets-2.4.5 lib/core/facets/hash/traverse.rb
mack-facets-0.8.2 lib/gems/facets-2.4.5/lib/core/facets/hash/traverse.rb