Sha256: 142a58087f2f91cb4e3bcdbc9ada92d6ba5273b1f9090bc844e2f318406d39d5

Contents?: true

Size: 784 Bytes

Versions: 26

Compression:

Stored size: 784 Bytes

Contents

class Hash

  # Returns a random key.
  #
  #   {:one => 1, :two => 2, :three => 3}.pick_key  #=> :three
  #
  def rand_key
    keys.at( rand(keys.size) )
  end

  # Delete a random key-value pair, returning the key.
  #
  #   a = {:one => 1, :two => 2, :three => 3}
  #   a.pick_key!  #=> :two
  #   a            #=> {:one => 1, :three => 3}
  #
  def rand_key!
    k,v = rand_pair
    delete( k )
    return k
  end

  alias_method( :pick_key, :rand_key! )

end


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

  require 'test/unit'

  class TCHash < Test::Unit::TestCase

    def test_rand_key
      h = { :a=>1, :b=>2, :c=>3 }
      10.times { assert( h.keys.include?( h.rand_key ) ) }
    end

  end

=end

Version data entries

26 entries across 26 versions & 1 rubygems

Version Path
facets-1.0.0 lib/facet/hash/rand_key.rb
facets-0.9.0 lib/nano/hash/rand_key.rb
facets-1.0.3 packages/core/lib/facet/hash/rand_key.rb
facets-1.2.1 lib/facets/core/hash/rand_key.rb
facets-1.3.0 lib/facets/core/hash/rand_key.rb
facets-1.1.0 lib/facet/hash/rand_key.rb
facets-1.2.0 lib/facets/core/hash/rand_key.rb
facets-1.3.1 lib/facets/core/hash/rand_key.rb
facets-1.3.2 lib/facets/core/hash/rand_key.rb
facets-1.3.3 lib/facets/core/hash/rand_key.rb
facets-1.4.1 lib/facets/core/hash/rand_key.rb
facets-1.4.0 lib/facets/core/hash/rand_key.rb
facets-1.4.2 lib/facets/core/hash/rand_key.rb
facets-1.4.3 lib/facets/core/hash/rand_key.rb
facets-1.4.4 lib/facets/core/hash/rand_key.rb
facets-1.4.5 lib/facets/core/hash/rand_key.rb
facets-1.7.38 lib/facets/core/hash/rand_key.rb
facets-1.7.30 lib/facets/core/hash/rand_key.rb
facets-1.7.0 lib/facets/core/hash/rand_key.rb
facets-1.7.46 lib/facets/core/hash/rand_key.rb