require 'facets/core/symbol/to_proc'

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.rekey{ |k| k.to_s }  #=>  { "name"=>"Gavin", "wife"=>:Lisa }
  #   foo.inspect              #=>  { :name =>"Gavin", :wife=>:Lisa }
  #

  def rekey( meth=nil, &block )
    raise ArgumentError, "2 for 1" if meth and block
    dup.send(:rekey!, meth, &block)
  end

  # Synonym for Hash#rekey, but modifies the receiver in place (and returns it).
  #
  #   foo = { :name=>'Gavin', :wife=>:Lisa }
  #   foo.rekey!{ |k| k.to_s }  #=>  { "name"=>"Gavin", "wife"=>:Lisa }
  #   foo.inspect               #=>  { "name"=>"Gavin", "wife"=>:Lisa }
  #

  def rekey!( meth=nil, &block )
    meth = :to_sym unless meth or block
    raise ArgumentError, "2 for 1" if meth and block
    block = meth.to_sym.to_proc if meth
    keys.each do |k|
      nk = block[k]
      self[nk]=delete(k) if nk
    end
    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.rekey{|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.rekey!{|k|k.to_s}  )
      assert_equal( { "a"=>1, "b"=>2 }, foo )
    end

    def test_03
      foo = { :a=>1, :b=>2 }
      assert_equal( { "a"=>1, "b"=>2 }, foo.rekey(:to_s) )
      assert_equal( { :a =>1, :b=>2 }, foo  )
    end

    def test_04
      foo = { :a=>1, :b=>2 }
      assert_equal( { "a"=>1, "b"=>2 }, foo.rekey!(:to_s) )
      assert_equal( { "a"=>1, "b"=>2 }, foo )
    end

    def test_05
      foo = { "a"=>1, "b"=>2 }
      assert_equal( { :a=>1, :b=>2 }, foo.rekey! )
      assert_equal( { :a=>1, :b=>2 }, foo )
    end

  end

=end

