Hey all, just a simple question.
I have a loop that I am using in ruby and I would like to be able to break from this loop whenever I want to. I would like to be able to enter "stop" into the console and hit return and have the loop break.
The loop needs to loop as normal until this happens and should only stop when I type the command.
Also, I have had a few solutions that cause the loop to go as such
loop
input
loop
input
etc...
But I need
loop
loop
loop
ect...
input
stop.
Cheers in advance!
Martin
Breaking loop upon user entering "stop"
Page 1 of 14 Replies - 6304 Views - Last Post: 21 June 2012 - 03:49 PM
Replies To: Breaking loop upon user entering "stop"
#2
Re: Breaking loop upon user entering "stop"
Posted 25 March 2012 - 03:27 AM
loop do
input = gets.chomp
if input == "stop"
break
else
do_something_with(input)
end
end
#3
Re: Breaking loop upon user entering "stop"
Posted 25 March 2012 - 04:38 AM
Hey sepp, thanks for the assistance, unfortunatly this does not resolve my issue. If you check the posting, this does what the 1st example does, looping, while stopping for input, then continues looping - I need it to loop repeatedly and stop looping once the command has been entered. Any more help would be awesome!
Cheers
Martin
Cheers
Martin
#4
Re: Breaking loop upon user entering "stop"
Posted 25 March 2012 - 05:09 AM
Ah, I see what you mean now. You can do that using threads:
This only asks for input once and if the user enters something other than "stop", it will loop forever. If you don't want that, you can put the input = gets.chomp inside a loop as well.
input = nil
worker_thread = Thread.new do
while input != "stop"
puts "Looping"
end
end
input = gets.chomp
worker_thread.join
This only asks for input once and if the user enters something other than "stop", it will loop forever. If you don't want that, you can put the input = gets.chomp inside a loop as well.
#5
Re: Breaking loop upon user entering "stop"
Posted 21 June 2012 - 03:49 PM
My approach would have looked something like this:
I'm curious and just want to know myself if this would be a good/bad approach and why, I'm not yet THAT familiar with ruby threads and they're actually giving me a hard time in my own code now. (that's because it got to do with networking, getting kinda complex)
running = true # main loop running?
t = Thread.new do
input = ""
while input != "stop"
puts "Enter command:"
input = gets.chomp
running == false if input == "stop"
end
end
# main loop
while running
# whatever you want to do in your loop
end
I'm curious and just want to know myself if this would be a good/bad approach and why, I'm not yet THAT familiar with ruby threads and they're actually giving me a hard time in my own code now. (that's because it got to do with networking, getting kinda complex)
Page 1 of 1

New Topic/Question
Reply


MultiQuote


|