Sha256: 4b7f799da94d3aef50e98201d3ccdb380dc2f52771606da8125758202209f64c

Contents?: true

Size: 1.73 KB

Versions: 10

Compression:

Stored size: 1.73 KB

Contents

# TITLE:
#
#   Hash Traversal Extensions
#
# SUMMARY:
#
#   Traversal extensions for Hash class.
#
# CREDITS:
#
#   - Thomas Sawyer

#
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 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 (?)
  #++
  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" }
  #
  def traverse!(&b)
    self.replace( self.traverse(&b) )
  end

end



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

  require 'test/unit'

  class TestHashTraverse < 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-2.0.1 lib/core/facets/hash/traverse.rb
facets-2.0.0 lib/core/facets/hash/traverse.rb
facets-2.0.2 lib/core/facets/hash/traverse.rb
facets-2.0.5 lib/core/facets/hash/traverse.rb
facets-2.1.1 lib/core/facets/hash/traverse.rb
facets-2.1.2 lib/core/facets/hash/traverse.rb
facets-2.0.4 lib/core/facets/hash/traverse.rb
facets-2.1.0 lib/core/facets/hash/traverse.rb
facets-2.0.3 lib/core/facets/hash/traverse.rb
facets-2.1.3 lib/core/facets/hash/traverse.rb