Sha256: bacb89352057a21ffb0d3b5743abd076c4dfaf61d70ff91ec0abee33b2fbcc9f

Contents?: true

Size: 1.37 KB

Versions: 10

Compression:

Stored size: 1.37 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" }
  #   h.traverse { |k,v| [k.downcase, v] }
  #   h  #=> { "a"=>"A", "b"=>"B" }
  #
  def traverse(&b)
    inject({}) do |h,(k,v)|
      nk, nv = b[k,v]
      h[nk] = ( Hash === v ? v.traverse(&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" }
  #
  def traverse!( &yld )
    self.replace( self.traverse( &yld ) )
  end

end


#  _____         _
# |_   _|__  ___| |_
#   | |/ _ \/ __| __|
#   | |  __/\__ \ |_
#   |_|\___||___/\__|
#
=begin test

  require 'test/unit'

  class TCHash < Test::Unit::TestCase

    def test_traverse
      h = { "A" => "x", "B" => "y" }
      h2 = h.traverse { |k,v| [k.downcase, v.upcase] }
      e = { "a" => "X", "b" => "Y" }
      assert_not_equal( h, h2 )
      assert_equal( e, h2 )
    end

    def test_traverse!
      h = { "A" => "x", "B" => "y" }
      h.traverse! { |k,v| [k.downcase, v.upcase] }
      e = { "a" => "X", "b" => "Y" }
      assert_equal( e, h )
    end

  end

=end

Version data entries

10 entries across 10 versions & 1 rubygems

Version Path
facets-1.0.3 packages/core/lib/facet/hash/traverse.rb
facets-0.9.0 lib/nano/hash/traverse.rb
facets-1.0.0 lib/facet/hash/traverse.rb
facets-1.3.0 lib/facets/core/hash/traverse.rb
facets-1.1.0 lib/facet/hash/traverse.rb
facets-1.2.0 lib/facets/core/hash/traverse.rb
facets-1.2.1 lib/facets/core/hash/traverse.rb
facets-1.3.1 lib/facets/core/hash/traverse.rb
facets-1.3.2 lib/facets/core/hash/traverse.rb
facets-1.3.3 lib/facets/core/hash/traverse.rb