Sha256: f184ec2f0a21e30cd0c53b9493de47469b87ac19d9350df50d6d5c9f444f805b

Contents?: true

Size: 1.09 KB

Versions: 10

Compression:

Stored size: 1.09 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", "C"=>{"X"=>"X"}}
  #
  #   g = h.traverse{ |k,v| [k.downcase, v] }
  #
  #   g  #=> {"a"=>"A", "b"=>"B", "c"=>{"x"=>"X"}}
  #
  # NOTE: Hash#traverse is the same as `recursive.graph` and
  # might be deprecated in the future (if it ever works!)
  #
  # CREDIT: Trans

  def traverse(&block)
    inject({}) do |h,(k,v)|
      if Hash === v
        v = v.traverse(&block)
      elsif v.respond_to?(:to_hash)
        v = v.to_hash.traverse(&block)
      end
      nk, nv = block.call(k,v)
      h[nk] = 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!(&block)
    replace(traverse(&block))
  end

end

Version data entries

10 entries across 9 versions & 2 rubygems

Version Path
facets-glimmer-3.2.0 lib/core/facets/hash/traverse.rb
facets-3.1.0 lib/core/facets/hash/traverse.rb
facets-3.0.0 lib/core/facets/hash/traverse.rb
facets-2.9.3 lib/core/facets/hash/traverse.rb
facets-2.9.2 src/core/facets/hash/traverse.rb
facets-2.9.2 lib/core/facets/hash/traverse.rb
facets-2.9.1 lib/core/facets/hash/traverse.rb
facets-2.9.0 lib/core/facets/hash/traverse.rb
facets-2.9.0.pre.2 lib/core/facets/hash/traverse.rb
facets-2.9.0.pre.1 lib/core/facets/hash/traverse.rb