Pabi
Pabi

Reputation: 994

Stop a while loop when a specific term/word is detected in the string

I would like to know how to create a code in ruby that would stop the while loop not matter what is written as long as the gets string contains the word "yes".

This is what I have so far:

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

Thank you very much.

Upvotes: 2

Views: 2227

Answers (2)

verbad
verbad

Reputation: 95

I would recommend using #break since it's more useful in similar but slightly different cases. Using #until or #while with a condition implies that you're willing to loop until you see the breaking condition and until then the loop will be infinite.

What is slightly more common in practice is iterating over a file or and array and wanting to break prematurely if a condition is met but ending the loop when the array or file read is complete

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

There are variations on the file handling that will read the whole file at once or line by line as here but in any case the loop will exit if condition is matched or end of file is reached. If you really want an infinite loop that runs until condition is matched, you can use this same approach with while(1) do ...

Upvotes: 1

Jesus Castello
Jesus Castello

Reputation: 1113

I think this will work, btw until is the same as while but with a negative condition.

input = gets.chomp.downcase

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

Upvotes: 3

Related Questions