Alex Rivera | Logout

How can I shuffle an array/hash in Ruby?

Asked 2011-02-20T22:52:18.283
10

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?

Edit
Report

1 Answer

1

If you wanted to get crazy and write your own in-place shuffle method, you could 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 
answered 2013-05-31T06:29:17.157

Your Answer