module Random::HashExtensions

Random extensions for Hash class.

Public Instance Methods

at_rand()
Alias for: rand_value
at_rand!()
Alias for: rand_value!
pick()
Alias for: rand_value!
pick_key()
Alias for: rand_key!
pick_pair()
Alias for: rand_pair!
rand_key() click to toggle source

Returns a random key.

@example

{:one => 1, :two => 2, :three => 3}.pick_key  # => :three
# File lib/garcon/core_ext/random.rb, line 258
def rand_key
  keys.at(SecureRandom.random_number(keys.size))
end
rand_key!() click to toggle source

Delete a random key-value pair, returning the key.

@example

a = {:one => 1, :two => 2, :three => 3}
a.rand_key!  # => :two
a            # => {:one => 1, :three => 3}
# File lib/garcon/core_ext/random.rb, line 269
def rand_key!
  k,v = rand_pair
  delete(k)
  return k
end
Also aliased as: pick_key
rand_pair() click to toggle source

Returns a random key-value pair.

@example

{:one => 1, :two => 2, :three => 3}.pick  # => [:one, 1]
# File lib/garcon/core_ext/random.rb, line 282
def rand_pair
  k = rand_key
  return k, fetch(k)
end
rand_pair!() click to toggle source

Deletes a random key-value pair and returns that pair.

@example

a = {:one => 1, :two => 2, :three => 3}
a.rand_pair!  # => [:two, 2]
a             # => {:one => 1, :three => 3}
# File lib/garcon/core_ext/random.rb, line 294
def rand_pair!
  k,v = rand_pair
  delete(k)
  return k,v
end
Also aliased as: pick_pair
rand_value() click to toggle source

Returns a random hash value.

@example

{:one => 1, :two => 2, :three => 3}.rand_value  # => 2
{:one => 1, :two => 2, :three => 3}.rand_value  # => 1
# File lib/garcon/core_ext/random.rb, line 308
def rand_value
  fetch(rand_key)
end
Also aliased as: at_rand
rand_value!() click to toggle source

Deletes a random key-value pair and returns the value.

@example

a = {:one => 1, :two => 2, :three => 3}
a.at_rand!  # => 2
a           # => {:one => 1, :three => 3}
# File lib/garcon/core_ext/random.rb, line 319
def rand_value!
  k,v = rand_pair
  delete(k)
  return v
end
Also aliased as: pick, at_rand!
shuffle() click to toggle source

Returns a copy of the hash with values arranged in new random order.

@example

h = {:a=>1, :b=>2, :c=>3}
h.shuffle  # => {:b=>2, :c=>1, :a>3}
# File lib/garcon/core_ext/random.rb, line 335
def shuffle
  ::Hash.zip(
    keys.sort_by   { SecureRandom.random_number },
    values.sort_by { SecureRandom.random_number })
end
shuffle!() click to toggle source

Destructive shuffle_hash. Arrange the values in a new random order.

@example

h = {:a => 1, :b => 2, :c => 3}
h.shuffle!
h  # => {:b=>2, :c=>1, :a=>3}
# File lib/garcon/core_ext/random.rb, line 348
def shuffle!
  self.replace(shuffle)
end