I'm creating a module for a deck of cards. I want the Deck object to be able to accept another implementation of the shuffle method I have written below.
I was originally thinking that my shuffle method should accept a parameter that is any object that responds to shuffle. Is that a good approach here?
I'm not sure exactly how to approach this in Ruby.
module PlayingCards
class Deck
RANKS = [*2..10, 'Jack', 'Queen', 'King', 'Ace']
SUITS = %w{ Clubs Diamonds Hearts Spades }
attr_accessor :cards, :discarded
def initialize(options={})
@cards = []
@discarded = []
options[:number_decks] ||= 1
options[:number_decks].times do
(RANKS).product(SUITS).each do |rank, suit|
@cards << Card.new(rank, suit)
end
end
end
def shuffle()
cards.push(*discarded).shuffle!
discarded = []
self
end
end
end
This is the hand class that is responsible for drawing cards from the deck and also folding a hand.
module PlayingCards
class Hand
attr_accessor :deck, :draw_count, :cards, :discarded
def initialize(args = {})
@deck = args[:deck]
@discarded = args[:deck].discarded
@draw_count = args[:draw_count]
@cards = []
end
def draw
draw_count.times do
cards.push(deck.cards[0])
deck.cards.shift
end
cards
end
def fold
discarded.push(cards).flatten!
end
end
end
cardsas last line inshuffle, to return the value.!discardedvariable. My best guess is that each time youshuffle, it's possible that some cards will be discarded; but the deck should always be fully restored to its original state before re-shuffling?shufflemethod should return thediscardedlist. I would consider it more normal for such a method to returnself.