How can I shuffle an array / hash in Ruby?

In order to learn what is called? Is the object an array or hash created?

stack_of_cards = [] 

This is how I fill it:

 stack_of_cards << Card.new("A", "Spades", 1) stack_of_cards << Card.new("2", "Spades", 2) stack_of_cards << Card.new("3", "Spades", 3) ... 

Here is my map class:

 class Card attr_accessor :number, :suit, :value def initialize(number, suit, value) @number = number @suit = suit @value = value end def to_s "#{@number} of #{@suit}" end end 

I would like to shuffle the elements in this array / hash (what is called ?: S)

Any suggestions?

+7
source share
5 answers
 stack_of_cards.shuffle 

This is an array, see http://www.ruby-doc.org/core-1.8.7/classes/Array.html for more information.

I wrote a functional form that returns a new array, and the new one is shuffled. Instead, you can use:

 stack_of_cards.shuffle! 

... to shuffle the array in place.

+18
source

If you want to shuffle the hash, you can use something like this:

 class Hash def shuffle Hash[self.to_a.sample(self.length)] end def shuffle! self.replace(self.shuffle) end end 

I posted this answer since I always find this question if I search for a β€œruby shuffle hash code”.

+9
source

In addition to using the shuffle method, you can use the sort method:

 array.sort {|a, b| rand <=> rand } 

This can be useful if you are using an older version of Ruby where shuffle not implemented. As with shuffle! you can use sort! to work with an existing array.

+1
source

If you want to go crazy and write your own shuffle method in place, you can do something like this.

  def shuffle_me(array) (array.size-1).downto(1) do |i| j = rand(i+1) array[i], array[j] = array[j], array[i] end array end 
+1
source

For arrays:

 array.shuffle [1, 3, 2].shuffle #=> [3, 1, 2] 

For hashes:

 Hash[*hash.to_a.shuffle.flatten] Hash[*{a: 1, b: 2, c: 3}.to_a.shuffle.flatten(1)] #=> {:b=>2, :c=>3, :a=>1} #=> {:c=>3, :a=>1, :b=>2} #=> {:a=>1, :b=>2, :c=>3} # Also works for hashes containing arrays Hash[*{a: [1, 2], b: [2, 3], c: [3, 4]}.to_a.shuffle.flatten(1)] #=> {:b=>2, :c=>3, :a=>1} #=> {:c=>[3, 4], :a=>[1, 2], :b=>[2, 3]} 
+1
source

All Articles