Created
December 7, 2012 17:38
-
-
Save unixmonkey/4234969 to your computer and use it in GitHub Desktop.
Method to suppress STDOUT in a block
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| #!/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