require 'facets/core/hash/rand_key'

class Hash

  # Returns a random key-value pair.
  #
  #   {:one => 1, :two => 2, :three => 3}.pick  #=> [:one, 1]
  #
  def rand_pair
    k = rand_key
    return k, fetch(k)
  end

  # Deletes a random key-value pair and returns that pair.
  #
  #   a = {:one => 1, :two => 2, :three => 3}
  #   a.rand_pair!  #=> [:two, 2]
  #   a             #=> {:one => 1, :three => 3}
  #
  def rand_pair!
    k,v = rand_pair
    delete( k )
    return k,v
  end

  alias_method( :pick_pair, :rand_pair! )

end


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

  require 'test/unit'

  class TCHash < Test::Unit::TestCase

    def test_rand_pair
      h = { :a=>1, :b=>2, :c=>3 }
      10.times { k,v = *h.rand_pair; assert_equal( v, h[k] ) }
    end

  end

=end
