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

时间:2015-04-28 07:23:33

标签: ruby while-loop break

从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}."

但是这不起作用,因为你不能像“破解”一样将“放置”线放在“结束”的末尾。有什么建议吗?

感谢。

2 个答案:

答案 0 :(得分:0)

如何将字符串赋值给变量并在循环结束时将其打印出来?

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

答案 1 :(得分:0)

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

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