From: Wilson Bilkovich Date: 2006-03-17T06:20:34+09:00 Subject: Re: Card tricks with Ruby On 3/16/06, grrr wrote: > So suppose you have a deck of cards, that might have some number of cards. > > First the cards are shuffled, in effect placed in random order. > > Then the deck is split, ie. some number of cards are lifted from the top > of the deck and placed under the remaining cards. > > How would one implement this? I was thinking of using an array, but how to > shuffle the deck, and how to split the deck? > How about this as a starting point? class Card attr_reader :card_id def initialize(card_id) @card_id = card_id end end class Deck attr_reader :cards def initialize(card_count = 52) @cards = [] card_count.times {|i| @cards << Card.new(i)} shuffle end def shuffle @cards.sort! {rand} end def cut(offset = nil) top = @cards[0,(offset || @cards.length / 2)] @cards = (@cards - top) + top end end deck.cut defaults to cutting the deck in half. deck.cut(5) takes the top 5 cards and puts them on the bottom of the deck. In real life, the attr_reader is bad form, because it exposes the implementation of '@cards' to clients. You don't really want people shuffling the deck without calling Deck#shuffle. To fix that, you could make custom accessors, like: each_card, card_at(position), deal_card, etc.