The Art of Instant Reproduction

Something special happens when we supply the special filename “-” to IO.popen. Instead of starting an external program, the Ruby interpreter makes an exact copy of itself as a new process, running the same script as before:

IO.popen("-", "w+")

# Now there are two of me!
["fee", "fie", "foe"].each {|x| STDERR.puts x}

 # output: feefee
						fie
						foe
						fie
						foe
					

The duplicate script does not start at the beginning but from the point immediately after the IO.popen call. Parent and child are running overlapped in time—or if you prefer, at the same time—so there is no guarantee of the order in which their output to STDERR will appear. That's why we see their output interleaved. Here, one has rudely interrupted the other before ...

Get Sams Teach Yourself Ruby in 21 Days now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.