1

I understand that you can use the sleep(2) which pause x time before the code displays but I want it to execute and display codes line by line. Eg:

x = 1
y = 2

puts x + y #I want this line to show first
sleep(5) #Above line shows but waiting 5 seconds before showing below
puts x + y * 2 #After 5 seconds this line shows
sleep(10) #After 10 seconds etc
puts (x + y) * 2

This works great in C programming but not Ruby.

Sylar
  • 11,422
  • 25
  • 93
  • 166

1 Answers1

0

It's a buffering issue. Try adding $stdout.sync = true before you use puts. Setting sync to true disables buffering.

x = 1
y = 2

$stdout.sync = true

puts x + y
sleep(5)
puts x + y * 2
sleep(10)
puts (x + y) * 2

Or, you can flush stdout manually each time:

x = 1
y = 2

puts x + y
$stdout.flush
sleep(5)

puts x + y * 2 
$stdout.flush
sleep(10)

puts (x + y) * 2
$stdout.flush

For more info on Ruby buffering, check out this well-done answer.

Community
  • 1
  • 1
JKillian
  • 18,061
  • 8
  • 41
  • 74