Skip to content

Instantly share code, notes, and snippets.

@unixmonkey
Created December 7, 2012 17:38
Show Gist options
  • Select an option

  • Save unixmonkey/4234969 to your computer and use it in GitHub Desktop.

Select an option

Save unixmonkey/4234969 to your computer and use it in GitHub Desktop.
Method to suppress STDOUT in a block
#!/usr/bin/env ruby
#
# Creates a block that temporarily suppresses STDOUT
# This is useful if you want to run something that uses
# puts or print, but don't actually want it to print to screen
#
require 'stringio'
def quiet(&block)
orig_stdout = $stdout
new_stdout = StringIO.new
$stdout = new_stdout
begin
yield
ensure
$stdout = orig_stdout
end
new_stdout.string
end
# one line version
# def quiet(&block);o=$stdout;$stdout=n=StringIO.new;begin;yield;ensure;$stdout=o;end;n.string;end
def quiet_demonstration
n = 0
puts n = n + 1 # => 1
quiet do
puts n = n + 1 # => 2
end
puts n = n + 1
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment