ruby - when to use flush after writing to STDOUT? -
i know flush
does. takes data stored in buffer , writes standard output empty buffer. not clear me when needs done (shouldn't flushing done automatically interpreter). reading book ruby programming language , gives example of socket server:
require 'socket' host, port = argv begin stdout.print "connnecting..." stdout.flush s = tcpsocket.open(host,port) stdout.puts "done" local, peer = s.addr, s.peeraddr stdout.print "connected #{peer[2]}:#{peer[1]}" stdout.print "using local port #{local[1]}" begin sleep(0.5) msg = s.read_nonblock(4096) stdout.puts msg.chop rescue systemcallerror end loop stdout.print '> ' stdout.flush local = stdin.gets break if !local s.puts(local) s.flush response = s.readpartial(4096) puts(response.chop) end rescue puts $! ensure s.close if s end
why invoke flush after writing "connecting" stdout, not invoke flush after writing "done" stdout? seems arbitrary here. confusion is.
to ensure "connecting..." gets printed out before potentially long-running thing happens.
once you're connected it's less important immediate feedback, , you're flushing after ">" characters printed in response reading data.
Comments
Post a Comment