这是一个相当有名的。确定扑克手的等级。我创建了以下类Card
:
class Card
attr_accessor :suite, :rank, :value
def initialize(suite, rank, value)
@suite = suite
@rank = rank
@value = value
end
def to_s
puts "#{@value}, #{@suite}, #{@rank}"
end
end
Deck
:
class Deck
def initialize()
@cardsInDeck = 52
@deck = Array.new()
end
def add_card(card)
@deck.push(card)
end
def deck_size
@deck.length
end
def to_s
@deck.each do |card|
"#{card.rank}, #{card.suite}"
end
end
def shuffle_cards
@deck.shuffle!
end
def deal_cards
#Here I create a new hand object, and when popping cards from the deck
# stack I insert the card into the hand. However, when I want to print
# the cards added to the hand I get the following error:
# : undefined method `each' for #<Hand:0x007fa51c02fd50> (NoMethodError)from
# driver.rb:36:in `<main>'
@hand = Hand.new
for i in 0..51 do
card = @deck.pop
@cardsInDeck -= 1
puts "#{card.value}, #{card.rank}, #{card.suite}"
@hand.add_cards(card)
end
@hand.each do |index|
"#{index.value}, #{index.rank}, #{index.suite}"
end
puts "Cards In Deck: #{@cardsInDeck}"
end
end
Hand
require_relative 'deck'
require_relative 'card'
class Hand
def initialize()
@hand = Array.new()
end
def to_s
count = 0
@hand.each do |card|
"#{card.value}, #{card.rank}, #{card.suite}"
count += 1
end
end
def add_cards(card)
@hand.push(card)
end
def hand_size()
@hand.length
end
end
和驱动程序文件:
require 'logger'
require_relative 'card'
require_relative 'deck'
require_relative 'hand'
suite = ["Hearts", "Diamonds", "Clubs", "Spades"]
rank = ["Ace", 2, 3, 4, 5, 6, 7, 8, 9, 10, "Jack", "Queen", "King"]
deck = Deck.new()
suite.each do |i|
v = 1
rank.each do |j|
deck.add_card(Card.new(i, j, v))
v += 1
end
end
在Deck
类中,deal_card
方法,我不明白为什么循环数组会导致方法错误
@hand.each do |index|
"#{index.value}, #{index.rank}, #{index.suite}"
end
puts "Cards In Deck: #{@cardsInDeck}"