<?xml version="1.0" encoding="UTF-8"?>
<feed xml:lang="en-US" xmlns="http://www.w3.org/2005/Atom">
  <id>tag:www.refactormycode.com,2007:users1914</id>
  <link type="application/atom+xml" href="http://www.refactormycode.com/users/1914" rel="self"/>
  <title>k776</title>
  <updated>Wed Feb 03 02:34:27 -0800 2010</updated>
  <entry>
    <id>tag:www.refactormycode.com,2007:Code1166</id>
    <published>2010-02-03T02:34:27-08:00</published>
    <updated>2010-02-03T02:34:27-08:00</updated>
    <title>[Ruby] Silencing current output, but capture output from another process</title>
    <content type="html">&lt;p&gt;Is there a shorter way to do this? Basically, I don't want anything outputted to the current irb session, but I want the variable 'out' to be the output from the fork. Command 'puts capture_system('which', 'git')' should work at the end of it.&lt;/p&gt;

&lt;pre&gt;def self.capture_system(*args)
  args = args.flatten.compact.collect { |arg| arg.to_s }
  return false if args.blank?

  rd, wr = IO.pipe

  pid = fork do
    rd.close
    $stdout.reopen wr
    $stderr.reopen wr
    yield if block_given?
    exec(*args) rescue nil
    exit! 1 # never gets here unless exec threw or failed
  end

  wr.close
  out = String.new
  out &amp;lt;&amp;lt; rd.read until rd.eof?
  Process.wait
  raise unless $?.success?
  out
end
&lt;/pre&gt;</content>
    <author>
      <name>k776</name>
      <email>kieran776@gmail.com</email>
    </author>
    <link type="text/html" href="http://www.refactormycode.com/codes/1166-silencing-current-output-but-capture-output-from-another-process" rel="alternate"/>
  </entry>
</feed>

