Ruby测验游戏出现#<Question:0x0000022164ee9210>错误,求排查
问题分析与修复
你看到的#<Question:0x0000022164ee9210>不是运行错误,而是Ruby默认打印对象的字符串形式——当你直接输出Question类的实例时,Ruby会用这种格式显示对象的内存标识,而不是你期望的题目内容。
问题根源
在测试函数里,你写了puts question,这会输出整个Question对象,而不是对象的prompt属性。你需要输出的是题目提示文本,也就是question.prompt。
修复后的测试函数代码
def testing(questions) answer = "" score = 0 for question in questions puts question.prompt # 改为输出prompt属性 answer = gets.chomp() if answer == question.answer score +=1 end end puts "\n你答对了 #{score} 道题,总共 #{questions.length} 道题。" end testing(questions)
可选优化(自定义对象打印格式)
如果想以后直接puts question就能输出题目,可以给Question类添加to_s方法,覆盖Ruby的默认实现:
class Question attr_accessor :prompt, :answer def initialize(prompt,answer) @prompt = prompt @answer = answer end def to_s @prompt # 定义对象转为字符串时返回prompt内容 end end
这样原来的puts question就能正常输出题目了。
内容的提问来源于stack exchange,提问作者Awais
相关产品推荐
相关产品推荐

