P
Peter Marsh
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!):
class Deck
@@Cards =
['Two','Three','Four','Five','Six','Seven','Eight','Nine','Ten','Jack','Queen','King','Ace']
@@Suits = ['Spades','Hearts','Diamonds','Clubs']
def initialize
@top_card = -1
@deck = []
52.times do |card|
@deck << card
end
end
def draw
@top_card = @top_card + 1
if @top_card < 52
@deck[@top_card]
else
raise 'There are only 52 cards in a deck!'
end
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]
end
def set_card(card)
@top_card=card
end
end
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!):
class Deck
@@Cards =
['Two','Three','Four','Five','Six','Seven','Eight','Nine','Ten','Jack','Queen','King','Ace']
@@Suits = ['Spades','Hearts','Diamonds','Clubs']
def initialize
@top_card = -1
@deck = []
52.times do |card|
@deck << card
end
end
def draw
@top_card = @top_card + 1
if @top_card < 52
@deck[@top_card]
else
raise 'There are only 52 cards in a deck!'
end
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]
end
def set_card(card)
@top_card=card
end
end