Sha256: 7e26c0c2d1763b08a5b54222a375a70c3661eff29537a67c9518a229037dc33b

Contents?: true

Size: 1.08 KB

Versions: 22

Compression:

Stored size: 1.08 KB

Contents

#--
# Adapted from rand.rb by:
# * Ilmari Heikkinen <mailto:kig@misfiring.net>
# * Christian Neukirchen <mailto:chneukirchen@gmail.com>
#++

require 'facet/hash/rand_key'

class Hash

  # Returns a random hash value.
  #
  #   {:one => 1, :two => 2, :three => 3}.rand_value  #=> 2
  #   {:one => 1, :two => 2, :three => 3}.rand_value  #=> 1
  #
  def rand_value
    fetch( rand_key )
  end

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

  alias_method( :pick, :rand_value! )

  alias_method( :at_rand, :rand_value )
  alias_method( :at_rand!, :rand_value! )


end


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

  require 'test/unit'

  class TCHash < Test::Unit::TestCase

    def test_rand_value
      h = { :a=>1, :b=>2, :c=>3 }
      10.times { assert( h.values.include?( h.rand_value ) ) }
    end

  end

=end

Version data entries

22 entries across 22 versions & 1 rubygems

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