Module: Random::HashExtensions

Included in:
Hash
Defined in:
lib/standard/facets/random.rb

Overview

Random extensions for Hash class.

Instance Method Summary collapse

Instance Method Details

#rand_keyObject

Returns a random key.

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


265
266
267
# File 'lib/standard/facets/random.rb', line 265

def rand_key
  keys.at(Random.number(keys.size))
end

#rand_key!Object Also known as: pick_key

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

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


275
276
277
278
279
# File 'lib/standard/facets/random.rb', line 275

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

#rand_pairObject

Returns a random key-value pair.

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


287
288
289
290
# File 'lib/standard/facets/random.rb', line 287

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.

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


298
299
300
301
302
# File 'lib/standard/facets/random.rb', line 298

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.

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


311
312
313
# File 'lib/standard/facets/random.rb', line 311

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.

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


321
322
323
324
325
# File 'lib/standard/facets/random.rb', line 321

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.

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


338
339
340
# File 'lib/standard/facets/random.rb', line 338

def shuffle
  ::Hash.zip( keys.sort_by{Random.number}, values.sort_by{Random.number} )
end

#shuffle!Object

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

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


349
350
351
# File 'lib/standard/facets/random.rb', line 349

def shuffle!
  self.replace(shuffle)
end