catbat
catbat

Reputation: 93

Terminating Loop on Input

I'm trying to find a way to terminate a loop when the user hits 'x'+Enter. I want the loop to just keep running in the background until the user cancels it.

Something along these lines:

while gets.chomp != 'x'

    puts 'looping...'

    sleep 1

end

I'm a beginner with programming and have searched far and wide for how to do this so any help would be deeply appreciated.

Upvotes: 2

Views: 1002

Answers (1)

Niklas B.
Niklas B.

Reputation: 95358

You have to use threads for this:

Thread.new do
  while line = STDIN.gets
    break if line.chomp == 'x'
  end
  exit
end

# whatever you want to do in the background
# (or rather in the foreground, actually)
loop do
  puts "foo"
  sleep 1
end

The problem is that STDIN.gets blocks, so you can't do something else at the same time without parallelizing the program by using a background thread that only checks for input.

Upvotes: 5

Related Questions