
class Hash

  # Converts all keys in the Hash accroding to the given block.
  # If the block return +nil+ for given key, then that key will be
  # left intact.
  #
  #   foo = { :name=>'Gavin', :wife=>:Lisa }
  #   foo.normalize_keys{ |k| k.to_s }  #=>  { "name"=>"Gavin", "wife"=>:Lisa }
  #   foo.inspect                       #=>  { :name =>"Gavin", :wife=>:Lisa }
  #
  #--
  # Adapted from Gavin Sinclair's #convert_keys.
  #++
  def normalize_keys( &block )
    dup.send(:normalize_keys!, &block)
  end

  # Synonym for Hash#normalize_keys, but modifies the receiver in place (and returns it).
  #
  #   foo = { :name=>'Gavin', :wife=>:Lisa }
  #   foo.normalize_keys!{ |k| k.to_s }  #=>  { "name"=>"Gavin", "wife"=>:Lisa }
  #   foo.inspect                        #=>  { "name"=>"Gavin", "wife"=>:Lisa }
  #
  #--
  # Adapted from Gavin Sinclair's #convert_keys.
  #++
  def normalize_keys!( &block )
    keys.each{ |k|
      nk = block[k]
      self[nk]=delete(k) if nk
    }
    self
  end

end


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

  require 'test/unit'

  class TestHash < Test::Unit::TestCase

    def test_01
      foo = { :a=>1, :b=>2 }
      assert_equal( { "a"=>1, "b"=>2 }, foo.normalize_keys{|k|k.to_s} )
      assert_equal( { :a =>1, :b=>2 }, foo  )
    end

    def test_02
      foo = { :a=>1, :b=>2 }
      assert_equal( { "a"=>1, "b"=>2 }, foo.normalize_keys!{|k|k.to_s}  )
      assert_equal( { "a"=>1, "b"=>2 }, foo )
    end

  end

=end
