我得到这个错误#<Question:0x0000022164ee9210>
,据我所知,代码没有任何问题。
prompt1 = "Roses are what, \n a) Blue ,\n b) Red \n c)Orrange"
prompt2 = "Voilets are what, \n a) Blue ,\n b) Red \n c)Orrange"
prompt3 = "I love who ?, \n a)Them ,\n b) everyone \n c)You"
这是课堂上的问题
class Question
attr_accessor :prompt, :answer
def initialize(prompt,answer)
@prompt = prompt
@answer = answer
end
end
questions = [
Question.new(prompt1,"b"),
Question.new(prompt2, "a"),
Question.new(prompt3,"c")
]
这是一个测试函数,将检查答案。并显示结果。
def testing (questions)
answer = ""
score = 0
for question in questions
puts question
answer = gets.chomp()
if answer == question.answer
score +=1
end
end
puts "\n You got #{score} questions right. out of #{questions.length} questions. "
end
testing(questions)
2条答案
按热度按时间rlcwz9us1#
你的代码没有错误。您看到的是通过
puts
打印自定义对象的默认行为。这就是为什么-调用
puts
使用这些简单的规则将给定的对象打印到标准输出,根据IO#puts
:object.to_s
。由于对象既不是字符串也不是数组,因此
puts
调用其to_s
方法。自定义类(如
Question
类)默认将Object
作为其超类。这意味着它们继承了Object
的所有方法,包括Object#to_s
:[...]打印对象的类和对象id的编码。
不幸的是,措辞有点误导。
to_s
实际上并不 * 打印 * 任何东西,它只是 * 返回 * 一个字符串。然而,这个字符串正是你在
#<Question:0x0000022164ee9210>
中看到的-Question
是你的对象的类,0x0000022164ee9210
是编码的对象id。如果你想让
puts question
输出其他东西,比如它的prompt
,你可以在你的类中覆盖to_s
:上述措施将导致:
输出量:
在实现
to_s
时,请记住它应该只返回一个字符串。它不应该自己打印任何东西,即。请勿在to_s
内部调用puts
。laximzn52#
您正在查看
puts question
的输出。用
print question.prompt
代替