Ruby 在字符串中检测到特定术语/单词时停止while循环

Ruby 在字符串中检测到特定术语/单词时停止while循环,ruby,string,loops,while-loop,Ruby,String,Loops,While Loop,我想知道如何在ruby中创建一个代码,只要gets字符串包含yes这个词,它就可以停止while循环,而不管编写的是什么 这就是我到目前为止所做的: while start!="yes" #make it so it stops the loop even if ex:"Yes, please!!!" is inputed. #does stuff start=gets.chomp end 非常感谢。我认为这会起作用,顺便说一句,直到与while相同,但条件是否定的 input = g

我想知道如何在ruby中创建一个代码,只要gets字符串包含yes这个词,它就可以停止while循环,而不管编写的是什么

这就是我到目前为止所做的:

while start!="yes" #make it so it stops the loop even if ex:"Yes, please!!!" is inputed.
  #does stuff
  start=gets.chomp
end

非常感谢。

我认为这会起作用,顺便说一句,直到与while相同,但条件是否定的

input = gets.chomp.downcase

until input.include? 'yes'
  # does stuff
  input = gets.chomp.downcase
end

我建议使用break,因为它在类似但略有不同的情况下更有用。将until或while与条件一起使用意味着您愿意循环,直到看到中断条件为止,直到那时循环将是无限的

在实践中,更常见的是对文件或and数组进行迭代,如果满足条件,则希望提前中断,但在数组或文件读取完成时结束循环

while (line = file.gets) do
  break if line =~ /yes/ # matches if line contains 'yes' anywhere
end

在文件处理上有一些变化,它们将一次或一行一行地读取整个文件,但在任何情况下,如果条件匹配或达到文件结尾,循环都将退出。如果你真的想要一个无限循环,直到条件匹配为止,你可以用同样的方法来处理while1 do

您所拥有的一切都很好,但在输入while循环之前,必须将start指定给除yes以外的任何值。如果不这样做,将引发以下异常:未定义的局部变量或main:Object的方法“start”。