This page contains automated test results for code from O'Reilly's Ruby Cookbook. If this code looks interesting or useful, you might want to buy the whole book.

Shuffling an Array
CodeExpectedActual
[1,2,3].sort_by { rand }
[1, 3, 2] [1, 3, 2]
class Array
  def shuffle!
    each_index do |i| 
      j = rand(length-i) + i
      self[j], self[i] = self[i], self[j]
    end
  end
  def shuffle
    dup.shuffle!
  end  
end
class Card
  def initialize(suit, rank)
    @suit = suit
    @rank = rank
  end
  def to_s
    "#{@suit} of #{@rank}"
  end
end
class Deck < Array
  attr_reader :cards
  @@suits = %w{Spades Hearts Clubs Diamonds}
  @@ranks = %w{Ace 2 3 4 5 6 7 8 9 10 Jack Queen King}
  def initialize
    @@suits.each { |suit| @@ranks.each { |rank| self << Card.new(rank, suit) } }
  end
end
deck = Deck.new
deck.collect { |card| card.to_s } 
["Ace of Spades", "2 of Spades", "3 of Spades", "4 of Spades", ... ] ["Ace of Spades", "2 of Spades", "3 of Spades", "4 of Spades", "5 of Spades", "6 of Spades", "7 of Spades", "8 of Spades", "9 of Spades", "10 of Spades", "Jack of Spades", "Queen of Spades", "King of Spades", "Ace of Hearts", "2 of Hearts", "3 of Hearts", "4 of Hearts", "5 of Hearts", "6 of Hearts", "7 of Hearts", "8 of Hearts", "9 of Hearts", "10 of Hearts", "Jack of Hearts", "Queen of Hearts", "King of Hearts", "Ace of Clubs", "2 of Clubs", "3 of Clubs", "4 of Clubs", "5 of Clubs", "6 of Clubs", "7 of Clubs", "8 of Clubs", "9 of Clubs", "10 of Clubs", "Jack of Clubs", "Queen of Clubs", "King of Clubs", "Ace of Diamonds", "2 of Diamonds", "3 of Diamonds", "4 of Diamonds", "5 of Diamonds", "6 of Diamonds", "7 of Diamonds", "8 of Diamonds", "9 of Diamonds", "10 of Diamonds", "Jack of Diamonds", "Queen of Diamonds", "King of Diamonds"]
deck.shuffle!
deck.collect { |card| card.to_s } 
["6 of Clubs", "8 of Diamonds", "2 of Hearts", "5 of Clubs", ... ] ["6 of Clubs", "8 of Diamonds", "2 of Hearts", "5 of Clubs", "5 of Diamonds", "Ace of Spades", "6 of Spades", "Ace of Hearts", "8 of Hearts", "Queen of Spades", "9 of Hearts", "7 of Clubs", "5 of Hearts", "8 of Spades", "Ace of Clubs", "Jack of Clubs", "7 of Spades", "5 of Spades", "Queen of Clubs", "9 of Clubs", "Queen of Hearts", "10 of Hearts", "Jack of Hearts", "King of Spades", "10 of Clubs", "2 of Diamonds", "10 of Diamonds", "7 of Hearts", "9 of Diamonds", "King of Diamonds", "10 of Spades", "3 of Diamonds", "6 of Diamonds", "3 of Hearts", "2 of Clubs", "3 of Spades", "9 of Spades", "Jack of Spades", "4 of Spades", "Ace of Diamonds", "7 of Diamonds", "3 of Clubs", "4 of Diamonds", "King of Hearts", "8 of Clubs", "6 of Hearts", "Jack of Diamonds", "4 of Hearts", "Queen of Diamonds", "4 of Clubs", "King of Clubs", "2 of Spades"]