1

我开始:

    puts "Hello there, and what's your favorite number?"
    favnum = gets.to_i
    puts "Your favorite number is #{favnum}?" " A better favorite number is #{favnum + 1}!"
    puts "Now, what's your favorite number greater than 10?"
    favnumOverTen = gets.to_i
    if favnumOverTen < 10
        puts "Hey! I said GREATER than 10! Try again buddy."
    else
        puts "Your favorite number great than 10 is #{favnumOverTen}?"
        puts "A bigger and better number over 10 is #{favnumOverTen * 10}!"
puts "It's literally 10 times better!"
    end

这很好用,但是如果用户输入的数字小于 10,程序就会结束。我希望用户被提示再试一次,直到他们输入一个大于 10 的数字。我应该用循环来做到这一点吗?

这就是我所尝试的,但显然它是错误的:

    puts "Hello there, and what's your favorite number?"
    favnum = gets.to_i
    puts "Your favorite number is #{favnum}?" " A better favorite number is #{favnum + 1}!"
    puts "Now, what's your favorite number greater than 10?"
    favnumOverTen = gets.to_i
    if favnumOverTen < 10
    loop.do
        puts "Hey! I said GREATER than 10! Try again buddy."
        favnumOverTen = gets.to_i
    until favnumOverTen > 10
    else
        puts "Your favorite number great than 10 is #{favnumOverTen}?"
        puts "A bigger and better number over 10 is #{favnumOverTen * 10}!"
puts "It's literally 10 times better!"
    end
4

2 回答 2

4

这是一种比前两种方法短一点的方法:

puts "Now, what's your favorite number greater than 10?"
until (favnumOverTen = gets.to_i) > 10
  puts "Hey! I said GREATER than 10! try again buddy."
end

这是有效的,因为赋值返回分配给变量的值。

于 2012-04-04T00:06:08.213 回答
1

更好的解决方案是一次获得最喜欢的数字 10,然后像这样开始until循环检查favnumOverTen > 10

puts "What is your favorite number greater than 10?"
favnumOverTen = gets.to_i
until favnumOverTen > 10 do
  puts "Hey! I said GREATER than 10! Try again buddy."
  favnumOverTen = gets.to_i
end

这样,如果初始条目大于 10,则永远不会执行 until 循环(为您节省if语句)。

另外,正如您所知道的,使用驼峰式大小写(即favnumOverTen应该是favnum_over_ten)不被认为是惯用的 Ruby。

于 2012-04-03T23:57:03.083 回答