Sha256: ee64935e138e0c8f02a672a6c9ca11eeb778dbb5833c73c076abb69d3d52ad34

Contents?: true

Size: 1.1 KB

Versions: 8

Compression:

Stored size: 1.1 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

8 entries across 8 versions & 1 rubygems

Version Path
facets-2.8.2 lib/core/facets/hash/traverse.rb
facets-2.8.1 lib/core/facets/hash/traverse.rb
facets-2.8.0 lib/core/facets/hash/traverse.rb
facets-2.7.0 lib/core/facets/hash/traverse.rb
facets-2.6.0 lib/core/facets/hash/traverse.rb
facets-2.5.0 lib/core/facets/hash/traverse.rb
facets-2.5.1 lib/core/facets/hash/traverse.rb
facets-2.5.2 lib/core/facets/hash/traverse.rb