0

I'm using Docopt in Ruby to parse my command options, and later in the script I am getting console input using gets.chomp. The problem is that all of the args from the running the program are still left in ARGF after Docopt does its parsing with options = Docopt::docopt(doc), and doing a gets command takes from ARGF before it tries gets'ing from STDIN.

I've tried to clear ARGF, but doing ARGF.gets for some reason tries to run the input as a command. I think clearing ARGF or using another input method could both be solutions, but I haven't found anything yet. I have to imagine that I'm not the first to try to get interactive command line input in Ruby with Docopt, so I'm hoping the answer is out there.

Some more code for those who would like it:

#!/usr/bin/ruby

require 'docopt'

doc=<<eos
Usage:
account_creator.rb --noldap                           [options]

Options:
-h, --help                  Show help page
-l, --ldap
-n, --noldap
-s SERVER                 With or without http[s]://, followed by port
--ad
--od
-d NUM
-u USER
-p PASS
-o OUTPUT-FILE             Default behavior is to append output to file if it exists
eos

options = {}
begin
  options = Docopt::docopt(doc)
rescue Docopt::Exit => e
  puts e.message
  exit 1
end

if options['-u']
  username = options['-u']
else
  while username.eql? '' or username == nil
    puts "Enter Username:"
    username = Kernel.gets.chomp.strip
  end
end

1 Answers1

0

This is unrelated to docopt. Try it on its own:

$ cat test.rb
#!/usr/bin/ruby

puts "Enter Username:"
username = gets

$ ./test.rb something
Enter Username:
./test.rb:4:in `gets': No such file or directory - something (Errno::ENOENT)
        from ./test.rb:4:in `gets'
        from ./test.rb:4:in `<main>'

Kernel.gets in ruby uses ARGF.gets. Using STDIN.gets should get you your expected behavior. See this SO question.

Community
  • 1
  • 1
user108471
  • 2,488
  • 3
  • 28
  • 41