Module: Random::HashExtensions
- Defined in:
- lib/garcon/core_ext/random.rb
Overview
Random extensions for Hash class.
Instance Method Summary collapse
-
#rand_key ⇒ Object
Returns a random key.
-
#rand_key! ⇒ Object
(also: #pick_key)
Delete a random key-value pair, returning the key.
-
#rand_pair ⇒ Object
Returns a random key-value pair.
-
#rand_pair! ⇒ Object
(also: #pick_pair)
Deletes a random key-value pair and returns that pair.
-
#rand_value ⇒ Object
(also: #at_rand)
Returns a random hash value.
-
#rand_value! ⇒ Object
(also: #pick, #at_rand!)
Deletes a random key-value pair and returns the value.
-
#shuffle ⇒ Object
Returns a copy of the hash with values arranged in new random order.
-
#shuffle! ⇒ Object
Destructive shuffle_hash.
Instance Method Details
#rand_key ⇒ Object
Returns a random key.
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.
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_pair ⇒ Object
Returns a random key-value pair.
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.
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_value ⇒ Object Also known as: at_rand
Returns a random hash value.
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.
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 |
#shuffle ⇒ Object
Returns a copy of the hash with values arranged in new random order.
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.
348 349 350 |
# File 'lib/garcon/core_ext/random.rb', line 348 def shuffle! self.replace(shuffle) end |