-3

例如在下面的代码中,我希望循环在条件评估为时立即结束true

x = "B"

until x == "A"
x = gets.chomp
puts "x is not equal to "A""
end

因此,如果用户输入"F",他们会得到,puts但如果他们输入"A",则puts不会输出。

4

2 回答 2

1

x = true分配truexsountil 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
于 2013-10-05T16:23:41.813 回答
0

关键字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"
于 2013-10-05T16:30:54.000 回答