Sha256: 08d238cb075eb9e76cf11a8bbb832c309fae62fe4fd2c906461b0a02f78da0b8

Contents?: true

Size: 856 Bytes

Versions: 22

Compression:

Stored size: 856 Bytes

Contents

require 'facet/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

Version data entries

22 entries across 22 versions & 1 rubygems

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