Ruby:如果while循环中断则放一条消息,如果while循环结束则放另一条消息

Posted

技术标签:

【中文标题】Ruby:如果while循环中断则放一条消息,如果while循环结束则放另一条消息【英文标题】:Ruby: Put one message if the while loop breaks and another message if the while loop ends 【发布时间】:2015-07-06 22:02:01 【问题描述】:

从 Ruby 开始,做一个我在网上找到的练习。最初只是制作一个脚本,生成一个随机数,让用户猜测它是什么,并反馈猜测是太高“热”还是太低“冷”。

我想通过只给用户 5 次猜测来补充这一点。所以我想要的是让剧本说“正确!你赢了!”如果用户猜对了,但说“对不起,你输了。正确答案是#answer。”如果你用尽了所有的猜测。

我的代码:

answer = rand(1..100)
guess_count = 5

puts answer

print "Pick a number between 1 and 100. You get 5 guesses. "
guess = gets.chomp.to_i

while guess_count > 1
  guess_count -= 1
  break puts "Correct! You win!" if guess == answer
  if guess > answer
    print "Hot. "
  else
    print "Cold. "
  end
  puts guess_count != 1 ? "Guess again. You have #guess_count guesses left." : "Guess again. You have 1 guess left."
  guess = gets.chomp.to_i
end puts "Sorry, you lose. The correct answer was #answer."

但这不起作用,因为您不能像使用“break”那样在“end”末尾添加“puts”行。有什么建议吗?

谢谢。

【问题讨论】:

【参考方案1】:

如何将字符串分配给一个变量并在循环结束时打印它?

output = "Sorry, you lose. The correct answer was #answer."
while guess_count > 1
  guess_count -= 1
  if guess == answer
    output = "Correct! You win!"
    break
  end
  if guess > answer
    print "Hot. "
  else
    print "Cold. "
  end
  puts guess_count != 1 ? "Guess again. You have #guess_count guesses left." : "Guess again. You have 1 guess left."
  guess = gets.chomp.to_i
end
puts output

【讨论】:

谢谢,这样就完成了。我想我更感兴趣的是是否有任何方法可以将所有内容都放在一条线上“当它到达循环结束时会发生这种情况,但如果循环提前退出就会被忽略”。但我想这不存在。【参考方案2】:

也许你可以使用这样的东西

def guess_number
  number, attempts = rand(1..100), 5

  while attempts != 0
    attempts -= 1
    puts "Your's guess ?"
    guess = gets.chomp.to_i
    if number == guess
      return "Correct! You win!"
    else
      if attempts != 0
        puts number < guess ? "Cold." : "Hot."
        puts "Guess again. You have #attempts attempts left."
      end
    end
  end
  "Sorry, you lose. The correct answer was #number."
end

【讨论】:

以上是关于Ruby:如果while循环中断则放一条消息,如果while循环结束则放另一条消息的主要内容,如果未能解决你的问题,请参考以下文章

如何在while循环中手动中断光标?

C#while循环不起作用[关闭]

如何从while循环内的if条件中断while循环?

使用外部事件中断 while 循环

do..while 循环中的继续和中断语句错误

如果等待太多,则在 x 次后中断循环