6

My ruby script gets certain inputs from command line arguments. It check if any of the command line argument is missing, then it prompts for an input from user. But i am not able to get input from user using gets.

Sample code: test.rb

name=""
ARGV.each do|a|
    if a.include?('-n')
        name=a
        puts "Argument: #{a}"
    end
end
if name==""
    puts "enter name:"
    name=gets
    puts name
end

Running script: ruby test.rb raghav-k

Results in the error:

test.rb:6:in `gets': No such file or directory - raghav-k (Errno::ENOENT)
    from test.rb:6:in `gets'
    from test.rb:6:in `<main>'

Any pointers in this direction will be really grateful Thanks Sandy

1 Answer 1

13

gets will only read from the real $stdin (ie the user) if there are no command line arguments. Otherwise it'll take those arguments as files to concatenate as a virtual $stdin.

You can use STDIN.gets to make sure you're always using the right function.

You can also delete the arguments from ARGV as you go (or remove them all in one go), your gets should work correctly.

Sign up to request clarification or add additional context in comments.

3 Comments

+1 Definitely a non-intuitive behaviour! I just found out that the correct way of reading from stdin is $stdin.gets
Yeah, that's the explicit way of forcing it to read from $stdin (which will probably avoid your arguments problem, I think.)
rjp: thanks for your inputs @Augusto: thanks. Using $stdin, it works perfectly...:):)

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.