Q:

How can I shuffle an array/hash in Ruby?

For learning purposes, what is this called? Is the object being created an array or a hash?
stack_of_cards = []

This is how I'm filling 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 Card 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'd like to shuffle the elements in this array/hash (what is this called? :S)
Any suggestions?

A:

stack_of_cards.shuffle

It is an Array, see http://www.ruby-doc.org/core-1.8.7/classes/Array.html for more information.
I've written the functional form, which returns a new Array, and it's the new one that's shuffled. You can instead use:
stack_of_cards.shuffle!

...to shuffle the array in-place.

A:

If you want to shuffle a 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've posted this answer since I always find this question if I search for "ruby shuffle hash".

