From: Robert Dober Date: 2007-04-24T17:15:15+09:00 Subject: Re: Cards Class On 4/23/07, Peter Marsh wrote: > Hi, I'm an utter newbie to Ruby (and OOP!) and I thought I'd share my > very first project. It's nothing special - just a simple class that > simulates a deck of cards, but I'd like to get your comments to see if > there's anything I can do better (enjoy!): This is indeed not a bad attempt at all, however ;) > > class Deck > @@Cards = > ['Two','Three','Four','Five','Six','Seven','Eight','Nine','Ten','Jack','Queen','King','Ace'] > @@Suits = ['Spades','Hearts','Diamonds','Club'] Personally I dislike class variables (I prefer class instance variables even if the make the code more clumpsy (clumpsier?)) but here it seems to me that constants would be in order, the name of the cards and suits are constant in the domain after all. Cards = %w{ Deuce Three Four Five ... Suits = %w{ Spades Hearts Diamonds Clubs } > > def initialize > @top_card = -1 > @deck = [] > 52.times do |card| > @deck << card > end I will play my personal Ace of Trumps here @deck = [*0..51] > end > > def draw > @top_card = @top_card + 1 @top_card += 1 > if @top_card < 52 > @deck[@top_card] > else > raise 'There are only 52 cards in a deck!' > end @deck[@top_card] or raise "There are only 42 cards in the deck ;)" > end > > def shuffle > @top_card = -1 > @deck = @deck.sort_by {rand} > end > > def suit > @@Suits[@top_card/13] > end > > def face > factor = @top_card/13 > index = @top_card - 13*factor > @@Cards[index] replace the three by Cards[ @top_card % 13 ] > end The above two methods seem wrong to me, is it not @deck[@top_card] that you want? > > def set_card(card) > @top_card=card > end No idea what that should do? If it were not for this method I would get rid of @top_card at all in your code and write it as follows def initialize; shuffle end def shuffle; @deck = [*0..51].sort_by{ rand } end def draw; @deck.shift or raise "Error only 42 cards" end def face; Cards[@deck.first % 13] end def suit; Suits[@deck.first / 13] end HTH Robert -- You see things; and you say Why? But I dream things that never were; and I say Why not? -- George Bernard Shaw