我正在寻找在Ruby中执行此操作的正确方法。我想创建一个if / else语句,它将一直循环,直到找到正确的答案。例如:
puts "Guess a number",prompt
$stdin.gets.chomp = x
if x == 5
puts "correct
else
# loop back to beginning and start over
end
答案 0 :(得分:4)
您可以使用while true
puts "Guess a number:"
if gets.chomp.to_i == 5
puts "correct"
break
end
puts "guessed wrong, please try again!"
end
语句循环,如果猜测数字,那么就像这样打破:
until
或使用puts "Guess a number:"
until gets.chomp.to_i == 5 do
puts "guessed wrong, please try again!"
end
puts "correct"
声明:
loop...do
正如@izaban所说,loop do
puts "Guess a number:"
if gets.chomp.to_i == 5
puts "correct"
break
end
puts "guessed wrong, please try again!"
end
也可以起作用:
var data = {} // your json data
答案 1 :(得分:0)
这是一个不使用break的解决方案:
guess = 0
first_run_through = true
until guess == 5
puts 'guessed wrong, please try again!' unless first_run_through
first_run_through = false
puts 'Guess a number'
guess = gets.chomp.to_i
end
puts 'correct'