当在字符串中检测到特定的 term/word 时停止 while 循环
Stop a while loop when a specific term/word is detected in the string
我想知道如何在 ruby 中创建一个代码,只要 gets 字符串包含 "yes".[=12 这个词,无论写什么都可以停止 while 循环=]
这是我目前拥有的:
while start!="yes" #make it so it stops the loop even if ex:"Yes, please!!!" is inputed.
#does stuff
start=gets.chomp
end
非常感谢。
我认为这会起作用,顺便说一句 until
与 while
相同,但有一个否定条件。
input = gets.chomp.downcase
until input.include? 'yes'
# does stuff
input = gets.chomp.downcase
end
我建议使用#break,因为它在类似但略有不同的情况下更有用。将#until 或#while 与条件一起使用意味着您愿意循环直到看到中断条件,并且在此之前循环将是无限的。
实践中更常见的是遍历文件或数组,如果满足条件则希望过早中断,但在数组或文件读取完成时结束循环
while (line = file.gets) do
break if line =~ /yes/ # matches if line contains 'yes' anywhere
end
文件处理有变体,可以一次读取整个文件或像这里一样逐行读取,但无论如何,如果条件匹配,循环将退出 或 结束到达文件。如果您真的想要一个无限循环,直到条件匹配为止,您可以使用与 while(1) do ...
相同的方法
我想知道如何在 ruby 中创建一个代码,只要 gets 字符串包含 "yes".[=12 这个词,无论写什么都可以停止 while 循环=]
这是我目前拥有的:
while start!="yes" #make it so it stops the loop even if ex:"Yes, please!!!" is inputed.
#does stuff
start=gets.chomp
end
非常感谢。
我认为这会起作用,顺便说一句 until
与 while
相同,但有一个否定条件。
input = gets.chomp.downcase
until input.include? 'yes'
# does stuff
input = gets.chomp.downcase
end
我建议使用#break,因为它在类似但略有不同的情况下更有用。将#until 或#while 与条件一起使用意味着您愿意循环直到看到中断条件,并且在此之前循环将是无限的。
实践中更常见的是遍历文件或数组,如果满足条件则希望过早中断,但在数组或文件读取完成时结束循环
while (line = file.gets) do
break if line =~ /yes/ # matches if line contains 'yes' anywhere
end
文件处理有变体,可以一次读取整个文件或像这里一样逐行读取,但无论如何,如果条件匹配,循环将退出 或 结束到达文件。如果您真的想要一个无限循环,直到条件匹配为止,您可以使用与 while(1) do ...
相同的方法