Search code examples
rubyloopssleep

Ruby while loop with sleep


Given the following ruby:

$i = 0
$num = 3

while $i < $num  do
    puts "My loop just executed"
    sleep 10
    $i +=1
end

I would expect that every 10 seconds (plus execution time) I would get "My loop just executed" printed to my console until $i = 3

My loop just executed
# sleeps for 10 seconds
My loop just executed
# sleeps for 10 seconds
My loop just executed
# sleeps for 10 seconds

However what actually happens is the script runs, nothing is printed to console until $i = 3 and then i get 3 lines printed at once:

My loop just executed
My loop just executed
My loop just executed

I can't understand why it wont print after each loop as oppose to printing all at the end?

Why is this and how can I get it to work as I am expecting it to? Any help would be appreciated


Solution

  • The console output is buffered and nobody promised to IO#flush it for you:

    $i = 0
    $num = 3
    
    while $i < $num  do
        $stdout.puts "My loop just executed"
        $stdout.flush
        sleep 10
        $i +=1
    end