我的代码出现问题,似乎无法弄清楚我需要改变什么。这是我的三个文件,底部是我得到的错误。我有完全相同的代码18次,其中一半给我这个错误。
初始化等级,套装和符号
def initialize(the_rank, the_suit)
@rank = the_rank
@suit = the_suit
@symbols = [nil, nil, '2', '3', '4', '5', '6', '7', '8', '9', '10', 'J', 'Q', 'K', 'A']
end
新文件Pokerhand.rb: 要求" ./常数" 要求" ./卡" 要求" ./ Deck" 要求" ./ CardSpaceship"
class PokerHand < Deck
include Constants
attr_reader :hand_type
def initialize(the_cards)
@cards = [ ]
@hand_type = UNCLASSIFIED
for card in the_cards
@cards << card
end
end
# Straight
elsif @cards[0].rank == @cards[1]+1.rank &&
@cards[1].rank == @cards[2]+1.rank &&
@cards[2].rank == @cards[3]+1.rank &&
@cards[3].rank == @cards[4]+1.rank
@hand_type = STRAIGHT
end
end
新文件test2.rb:
class PokerHand < Deck
include Constants
attr_reader :hand_type
def initialize(the_cards)
@cards = [ ]
@hand_type = UNCLASSIFIED
for card in the_cards
@cards << card
end
end
# Determine hand type of PokerHand object.
def classify
@cards.sort!
# Straight
def test_7
arr7 = [Card.new(2, "C"), Card.new(3, "S"),
Card.new(4, "H"), Card.new(5, "D"),
Card.new(6, "S")]
ph7 = PokerHand.new(arr7)
ph7.classify
assert_equal STRAIGHT , ph7.hand_type
end
收到错误:
TestClass#test_7:
NoMethodError: undefined method `rank' for 1:Fixnum
PokerHand.rb:79:in `classify'
test2.rb:76:in `test_7'
答案 0 :(得分:1)
首先,您的PokerHand#initialize
方法非常困惑。除了@cards
之外,您永远不会将任何值分配给[ ]
,这是一个空数组。因此,当您调用classify
方法时,@cards
仍为[ ]
,因此@cards[0]
,@cards[1]
或@cards[x]
为任何值x
的{{1}}始终为nil
。 PokerHand#initialize
看起来应该更像这样:
def initialize(cards)
@cards = cards
@hand_type = UNCLASSIFIED
end
其次,你构成同花顺的逻辑是不正确的。目前,只有当手中的每张牌完全相同时才计算同花顺,例如,三张心中的五张副本。