|
[Date Prev] [Date Next] [Thread Prev] [Thread Next] [Date Index] [Thread Index]
|
Re: [PhillyOnRails] a little hold 'em code ... help please
|
Minor ruby idiom as you asked for feedback =)
On Nov 21, 2005, at 1:22 PM, Chris Braddock wrote:
A Ruby/OO noob could use a little help here.
I saw the Hold 'Em trainer project on the community wiki. Thought
I might kick it around a bit.
I think I have some basic code to get a deck shuffled but there is
one place where I'm a little confused (see comments) and I'd love
to get some code critiques as I'm just fumbling my way through this
right now.
#holdem.rb
class Card
attr_reader :suit, :rank
def initialize(suit, rank)
@suit = suit
@rank = rank
end
end
class Deck
attr_reader :deck
SUITS = ["C","D","H","S"]
RANKS = ["2","3","4","5","6","7","8","9","10","J","Q","K","A"]
A very common idiom for constructing lists of strings is to use %w, a la
irb(main):001:0> ary = %w(2 3 4 5 6 7 8 9 10 J Q K A)
=> ["2", "3", "4", "5", "6", "7", "8", "9", "10", "J", "Q", "K", "A"]
irb(main):002:0>
The %W variant allows interpolation:
irb(main):002:0> ace = 'A'
=> "A"
irb(main):003:0> ary2 = %W(2 3 4 5 6 7 8 9 10 J Q K #{ace})
=> ["2", "3", "4", "5", "6", "7", "8", "9", "10", "J", "Q", "K", "A"]
irb(main):004:0>
It just saves some typing for a common case =)
def initialize
@deck = Array.new
SUITS.each do |suit|
RANKS.each do |rank|
@deck[@deck.length] = Card.new(suit, rank)
end
end
It might be clearer to say
@deck << Card.new(suit, rank)
however
self
end
def shuffle
deck_shuffled = Array.new
deck_length_orig = @deck.length
while deck_shuffled.length < deck_length_orig
rand_card = rand(@deck.length)
deck_shuffled << @deck[rand_card]
@deck.delete_at(rand_card)
end
@deck.replace(deck_shuffled)
end
end
deck = Deck.new
deck.shuffle
# why do I need to use deck.deck if I'm returning self on
initialize? have pointer to self object and that's <> the array?
why not define each for the deck?
class Deck
def each &block
@deck.each &block
end
end
or
class Deck
def each
@deck.each { |card| yield card }
end
end
I like the first, personally, but either works, and each,
traditionally, uses yield not an explicit param
deck.deck.each do |card|
print(card.rank, card.suit)
print "," unless deck.deck.index(card) == deck.deck.length - 1
end
puts
print("total cards: ", deck.deck.length)
ditto define length on deck =)
puts
_______________________________________________
talk mailing list
talk@phillyonrails.org
http://lists.phillyonrails.org/mailman/listinfo/talk
_______________________________________________
talk mailing list
talk@phillyonrails.org
http://lists.phillyonrails.org/mailman/listinfo/talk
|
|