我正在用Ruby做一个问答游戏,有一个检查答案和奖励分数的测试方法,我得到了这个错误#< Question:0x0000022164ee9210>

5lhxktic  于 12个月前  发布在  Ruby
关注(0)|答案(2)|浏览(101)

我得到这个错误#<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)
rlcwz9us

rlcwz9us1#

你的代码没有错误。您看到的是通过puts打印自定义对象的默认行为。
这就是为什么-调用puts使用这些简单的规则将给定的对象打印到标准输出,根据IO#puts

  • String:写入字符串。
  • 既不是字符串也不是数组:写入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

class Question
  # ...

  def to_s
    prompt
  end
end

上述措施将导致:

question = Question.new("Roses are ...\n a) Blue\n b) Red\n c) Orange", "b")
puts question

输出量:

Roses are ...
 a) Blue
 b) Red
 c) Orange

在实现to_s时,请记住它应该只返回一个字符串。它不应该自己打印任何东西,即。请勿在to_s内部调用puts

laximzn5

laximzn52#

您正在查看puts question的输出。
print question.prompt代替

相关问题