Module: Random::HashExtensions

Defined in:
lib/garcon/core_ext/random.rb

Overview

Random extensions for Hash class.

Instance Method Summary collapse

Instance Method Details

#rand_keyObject

Returns a random key.

Examples:

{:one => 1, :two => 2, :three => 3}.pick_key  # => :three


258
259
260
# File 'lib/garcon/core_ext/random.rb', line 258

def rand_key
  keys.at(SecureRandom.random_number(keys.size))
end

#rand_key!Object Also known as: pick_key

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

Examples:

a = {:one => 1, :two => 2, :three => 3}
a.rand_key!  # => :two
a            # => {:one => 1, :three => 3}


269
270
271
272
273
# File 'lib/garcon/core_ext/random.rb', line 269

def rand_key!
  k,v = rand_pair
  delete(k)
  return k
end

#rand_pairObject

Returns a random key-value pair.

Examples:

{:one => 1, :two => 2, :three => 3}.pick  # => [:one, 1]


282
283
284
285
# File 'lib/garcon/core_ext/random.rb', line 282

def rand_pair
  k = rand_key
  return k, fetch(k)
end

#rand_pair!Object Also known as: pick_pair

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

Examples:

a = {:one => 1, :two => 2, :three => 3}
a.rand_pair!  # => [:two, 2]
a             # => {:one => 1, :three => 3}


294
295
296
297
298
# File 'lib/garcon/core_ext/random.rb', line 294

def rand_pair!
  k,v = rand_pair
  delete(k)
  return k,v
end

#rand_valueObject Also known as: at_rand

Returns a random hash value.

Examples:

{:one => 1, :two => 2, :three => 3}.rand_value  # => 2
{:one => 1, :two => 2, :three => 3}.rand_value  # => 1


308
309
310
# File 'lib/garcon/core_ext/random.rb', line 308

def rand_value
  fetch(rand_key)
end

#rand_value!Object Also known as: pick, at_rand!

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

Examples:

a = {:one => 1, :two => 2, :three => 3}
a.at_rand!  # => 2
a           # => {:one => 1, :three => 3}


319
320
321
322
323
# File 'lib/garcon/core_ext/random.rb', line 319

def rand_value!
  k,v = rand_pair
  delete(k)
  return v
end

#shuffleObject

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

Examples:

h = {:a=>1, :b=>2, :c=>3}
h.shuffle  # => {:b=>2, :c=>1, :a>3}


335
336
337
338
339
# 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!Object

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

Examples:

h = {:a => 1, :b => 2, :c => 3}
h.shuffle!
h  # => {:b=>2, :c=>1, :a=>3}


348
349
350
# File 'lib/garcon/core_ext/random.rb', line 348

def shuffle!
  self.replace(shuffle)
end