Sha256: 87b7b036bb409a7caaacbcf6fa4f7a0c547e765697006f1314098bfa923c5d80

Contents?: true

Size: 1.07 KB

Versions: 4

Compression:

Stored size: 1.07 KB

Contents

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

  # Return the key-value pairs with _keys_ and _values_
  # shuffled independedly.
  #
  #   require 'facet/hash/shuffle'
  #
  #   {:a=>1, :b=>2, :c=>3}.shuffle_hash_pairs  
  #
  # produces
  #
  #   [[:a, 3], [:b, 1], [:c, 2]]
  #
  def shuffle_hash_pairs
    keys.shuffle.zip(values.sort_by{Kernel.rand})
  end

  # Returns a copy of the hash with _values_ arranged
  # in new random order.
  #
  #   require 'facet/hash/shuffle'
  #
  #   h = {:a=>1, :b=>2, :c=>3}
  #   h.shuffle_hash  #=> {:b=>2, :c=>1, :a>3}
  #
  def shuffle_hash
    shuffled = {}
    shuffle_hash_pairs.each{|k, v| shuffled[k] = v }
    shuffled
  end

  # Destructive shuffle_hash.  Arrange the values in 
  # a new random order.
  #
  #   require 'facet/hash/shuffle'
  #
  #   h = {:a => 1, :b => 2, :c => 3}
  #   h.shuffle_hash!
  #   h  #=> {:b=>2, :c=>1, :a=>3}
  #
  def shuffle_hash!
    shuffle_hash_pairs.each{ |k, v| self[k] = v }
    self
  end

end

Version data entries

4 entries across 4 versions & 1 rubygems

Version Path
facets-0.6.3 lib/facet/hash/shuffle.rb
facets-0.7.0 lib/facet/hash/shuffle.rb
facets-0.7.1 lib/facet/hash/shuffle.rb
facets-0.7.2 lib/facet/hash/shuffle.rb