例如在下面的代码中,我希望循环在条件评估为时立即结束true
x = "B"
until x == "A"
x = gets.chomp
puts "x is not equal to "A""
end
因此,如果用户输入"F"
,他们会得到,puts
但如果他们输入"A"
,则puts
不会输出。
x = true
分配true
给x
sountil x = true
等价于until true
.
因此,在以下行中替换=
为:==
until x = true
->
until x == true
或者,它永远不会结束。
更新
使用以下代码:
while true
x = gets.chomp
break if x == 'A'
puts 'x is not equal to "A"'
end
或者
until (x = gets.chomp) == 'A'
puts 'x is not equal to "A"'
end
关键字break
将从循环中退出。
x = false
a = 0
b = 0
until x # is a boolean already so no need for == true
a = 1
b = 2
# code here that could change state of x
break if x # will break from loop if x == anything other than false or nil
a = 2
b = 1
end
显然,这不是好的代码,但其中有一些有用的概念,您可能可以从中找出来。
编辑
为了响应您的新代码,正确使用 foruntil
循环。
puts "x is not equal to 'A'" until (x = gets.chomp) == "A"