Why does this code work (I see the output 1 2 3):
for i in 1..3 Thread.new{ puts i } end However, the following code does not produce the same output (I do not see the output 1 2 3)?
for i in 1..3 Thread.new{ sleep(5) puts i } end When you hit the end of the script, Ruby exits. If you add sleep 10 after the final loop, you can see the output show up. (Albeit, as 3 each time, because the binding to i reflects the value at the end of processing, and the sleep causes a thread switch back to the loop.)
You might want something like:
threads = [] for i in 1..3 threads << Thread.new { sleep 5 puts i } end threads.map {|t| t.join } That will wait for all the threads to terminate before exiting.