Skip to content

Instantly share code, notes, and snippets.

@MaxPleaner
Last active February 9, 2016 10:29
Show Gist options
  • Save MaxPleaner/f1eda6e9e0c53948165d to your computer and use it in GitHub Desktop.
Save MaxPleaner/f1eda6e9e0c53948165d to your computer and use it in GitHub Desktop.
with_stdin (pipe to gets.chomp)
# 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