在Ruby中遇到一个直到循环的条件

时间:2013-10-05 16:20:22

标签: ruby loops

例如,在下面的代码中,我希望一旦条件评估为true

,循环就会结束
x = "B"

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

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

2 个答案:

答案 0 :(得分:1)

x = truetrue分配给x,因此until 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

答案 1 :(得分: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

显然,这不是一个好的代码,但有一些有用的概念,你可能会捞出来。

修改

为了响应您的新代码,它适用于until循环。

puts "x is not equal to 'A'" until (x = gets.chomp) == "A"