这是一个相当熟悉的人。确定扑克牌的等级。我创建了以下类: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}"
答案 0 :(得分:0)
@hand
是Hand
的一个实例,并且没有为each
定义的实例方法Hand
,因此这就是@hand.each
生成{的原因{1}}错误。
答案 1 :(得分:0)
我的回答并不是非常直接的错误,但在这种情况下可以帮助你。
您的方法deal_cards
是依赖注入可以发挥作用的地方。原始设计Deck
对Hand
有很强的依赖性,这种依赖性并不好,也很难测试。您需要像
def deal_cards(hand=nil)
@hand = hand || Hand.new
# Others
end
通过这个你可以接受Hand
之外的实例,比如Foot
,只要有人可以用脚打牌!
您也可以单独测试此方法,而无需编写Hand类。
最好对类进行单元测试而不是手动检查,然后您可以在测试期间将任何您喜欢的实例注入此方法。