为什么这个代码在我第一次回答gets.chomp时出错,但是如果我重复我的回答呢?

时间:2014-08-06 16:12:57

标签: ruby

下面的代码在第一次"ERROR. Please enter a proper pronoun: male, female, it or they"提示答案时打印在while循环中设置的gets.chomp,但如果您第二次重复该答案则有效。我错过了什么?

def essay_writer(title, person, date, thesis_statement)
  puts "Welcome! Is your person male, female, it or they?"
  noun = gets.chomp
  noun.downcase! 
  while noun != ("male" || "female" || "it" || "they")
    puts "ERROR.  Please enter a proper pronoun: male, female, it or they"
    noun = gets.chomp
    noun.downcase!
    break if noun == "male" || noun == "female" || noun == "it" || noun == "they"
  end
  if noun == "male"
    pronoun = "I've learned a lot about him."
  elsif noun == "female"
    pronoun = "I've learned a lot about her."
  elsif noun == "it"
    pronoun = "I've learned a lot about it."
  elsif noun == "they"
    pronoun = "I've learned a lot about them."
  else
    puts "Fatal Error"
  end 
  person_new = "#{person}" + "'s contribution was very important."
  return "#{title}\n\n" + "#{person} was important in #{date}. #{pronoun} #{thesis_statement} #{person_new}" 
end 

puts essay_writer("Reef is a Puppy", "Reef", 2009, "Reef is an abnormally smart dachshund, renowned for his speed, and has won many local races.") == "Reef is a Puppy\n\n" "Reef was important in 2009. I've learned a lot about him. Reef is an abnormally smart dachshund, renowned for his speed, and has won many local races. Reef's contribution was very important."

1 个答案:

答案 0 :(得分:2)

这已被破坏:while noun != ("male" || "female" || "it" || "they")

这不是你如何针对Ruby或任何语言中的多个其他值测试值。它在语法上是有效的,但它并没有做你认为它正在做的事情。您现在拥有的内容将始终首先评估("male" || "female" || "it" || "they"),从而产生值"male",这意味着您当前的循环与此相同:

while noun != "male"

与此同时,您已经循环中正确地写了break if noun == "male" || noun == "female" || noun == "it" || noun == "they"

您需要以下任一项:

while noun != "male" && noun != "female" && noun != "it" && noun != "they"

或者:

while !%w(male female it they).include?(noun)