以下是生成错误的类定义:
class Hand
attr_accessor :hand_cards, :hand_value
def intitialize
@hand_cards = []
@hand_value = 0
end
def to_s
"The hand is #{hand_cards} and has a value of #{hand_value}"
end
def add_card(new_card)
hand_cards << new_card
end
def calculate_hand_value
hand_cards.each do |card|
case card[1]
when '2'
hand_value += 2
when '3'
hand_value += 3
when '4'
hand_value += 4
when '5'
hand_value += 5
when '6'
hand_value += 6
when '7'
hand_value += 7
when '8'
hand_value += 8
when '9'
hand_value += 9
when '10'
hand_value += 10
when 'J'
hand_value += 10
when 'Q'
hand_value += 10
when 'K'
hand_value += 10
when 'A'
if hand_value <= 10
hand_value += 11
else
hand_value += 1
end
end
end
end
end
当我创建一个Hand对象并尝试使用add_card方法时,我收到此错误:OO-blackjack2.rb:43:in add_card': undefined method
&lt;&lt;&lt; for nil:NilClass(NoMethodError)
来自OO-blackjack2.rb:108:在''
我认为这意味着hand_cards的值为nil,但根据我的初始化定义,它应设置为空数组并可通过attr_accessor访问。如果您需要查看整个计划,请告诉我。感谢。
答案 0 :(得分:1)
您拼写构造函数intitialize
,这意味着它不会被.new
方法调用。它应该是initialize
。