Last active
February 9, 2016 10:29
-
-
Save MaxPleaner/f1eda6e9e0c53948165d to your computer and use it in GitHub Desktop.
with_stdin (pipe to gets.chomp)
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
# credit http://stackoverflow.com/a/16950202/2949493 | |
def with_stdin | |
stdin = $stdin # remember $stdin | |
$stdin, write = IO.pipe # create pipe assigning its "read end" to $stdin | |
yield write # pass pipe's "write end" to block | |
ensure | |
write.close # close pipe | |
$stdin = stdin # restore $stdin | |
end | |
# usage: | |
# with_stdin { |stdin| stdin.puts "text"; gets.chomp } | |
# which will return: "text" | |
# Note the "return" word cannot be used in the block | |
# It turns out this was not the solution i was looking for. Instead, I'm using Shell | |
require "shell" | |
sh = Shell.new | |
result = (sh.system("echo exit") | sh.system("irb")).to_s |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment