Ruby中的Card类
我是ruby的新手,正在开发一个card类。在大多数情况下,当我使用一个数字来定义一个秩时,它都能工作,但是当我将秩定义为K(King)时,它会返回一条错误消息(未初始化常量)。如果有人能告诉我,并向我解释我做错了什么,我将不胜感激 这是我的卡片课Ruby中的Card类,ruby,class,playing-cards,Ruby,Class,Playing Cards,我是ruby的新手,正在开发一个card类。在大多数情况下,当我使用一个数字来定义一个秩时,它都能工作,但是当我将秩定义为K(King)时,它会返回一条错误消息(未初始化常量)。如果有人能告诉我,并向我解释我做错了什么,我将不胜感激 这是我的卡片课 class Card attr_accessor :rank, :suit def initialize(the_rank, the_suit) @rank = the_rank @suit = the_suit
class Card
attr_accessor :rank, :suit
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
def rank
return @rank
end
def suit
return @suit
end
def color
if @suit == "C" || @suit == "S"
color = "Black"
else
color = "Red"
end
end
def to_s
return "#{@symbols[@rank]}#{@suit}"
end
end
这是一个简单的测试脚本,我有它运行的俱乐部7罚款,但不能运行的心脏杰克
c = Card.new(7, "C")
print c, "\n"
print c.rank, "\n"
print c.suit, "\n"
print c.color, "\n"
c = Card.new(J, "H")
print c, "\n"
print c.rank, "\n"
print c.suit, "\n"
print c.color, "\n"
而不是
c = Card.new(J, "H")
试一试
这是因为
J
没有任何意义,它不是一个定义的对象;但是字符串“J”
,Ruby将该对象识别为字符串,因此没有错误完全错误是什么?BBB.rb:13:in`':未初始化常量J(NameError),这是因为您有一行c=Card.new(J,“H”)
。应该是c=Card.new(“J”,“H”)
,我想应该是。注意:J
->“J”
当我尝试接收此消息时:AAA.rb:27:in`[]':当我尝试接收此消息时,没有将字符串隐式转换为整数(TypeError):AAA.rb:27:in`[]':没有将字符串隐式转换为整数(TypeError)收到此错误时,您正在执行哪行代码?BBB是我的测试脚本,AAA是类scriptOkay。。。。那没有回答我的问题。错误中的代码行是27。AAA.return“#{@symbols[@rank]}#{@suit}”中第27行上运行的实际代码是什么
c = Card.new("J", "H")