Sha256: 04e82d7c9e92cc6c18d15bc37369a9d78d2bff57b0ebe233fc0d8ee33f08ea76

Contents?: true

Size: 954 Bytes

Versions: 3

Compression:

Stored size: 954 Bytes

Contents

require 'facets/core/hash/self/zipnew'

class Hash

  # Returns a copy of the hash with _values_ arranged
  # in new random order.
  #
  #   h = {:a=>1, :b=>2, :c=>3}
  #   h.shuffle_hash  #=> {:b=>2, :c=>1, :a>3}
  #
  def shuffle
    Hash.zipnew( keys.sort_by{Kernel.rand}, values.sort_by{Kernel.rand} )
  end

  # Destructive shuffle_hash. Arrange the values in
  # a new random order.
  #
  #   h = {:a => 1, :b => 2, :c => 3}
  #   h.shuffle_hash!
  #   h  #=> {:b=>2, :c=>1, :a=>3}
  #
  def shuffle!
    self.replace( shuffle )
  end

end


#  _____         _
# |_   _|__  ___| |_
#   | |/ _ \/ __| __|
#   | |  __/\__ \ |_
#   |_|\___||___/\__|
#
=begin test

  require 'test/unit'

  class TCHash < Test::Unit::TestCase

    def test_shuffle
      h = {:a=>1, :b=>2, :c=>3 }
      assert_nothing_raised { h.shuffle }
    end

    def test_shuffle!
      h = {:a=>1, :b=>2, :c=>3 }
      assert_nothing_raised { h.shuffle! }
    end

  end

=end

Version data entries

3 entries across 3 versions & 1 rubygems

Version Path
facets-1.8.49 lib/facets/core/hash/shuffle.rb
facets-1.8.51 lib/facets/core/hash/shuffle.rb
facets-1.8.54 lib/facets/core/hash/shuffle.rb