Why is gets throwing an error when arguments are passed to my ruby script?

后端 未结 2 1014
情话喂你
情话喂你 2020-12-10 03:24

I\'m using gets to pause my script\'s output until the user hits the enter key. If I don\'t pass any arguments to my script then it works fine. However, if I

相关标签:
2条回答
  • 2020-12-10 03:58

    Ruby will automatically treat unparsed arguments as filenames, then open and read the files making the input available to ARGF ($<). By default, gets reads from ARGF. To bypass that:

    $stdin.gets
    

    It has been suggested that you could use STDIN instead of $stdin, but it's usually better to use $stdin.

    Additionally, after you capture the input you want from ARGV, you can use:

    ARGV.clear
    

    Then you'll be free to gets without it reading from files you may not have intended to read.

    0 讨论(0)
  • 2020-12-10 04:12

    The whole point of Kernel#gets is to treat the arguments passed to the program as filenames and read those files. The very first sentence in the documentation reads:

    Returns (and assigns to $_) the next line from the list of files in ARGV (or $*)

    That's just how gets works. If you want to read from a specific IO object (say, $stdin), just call gets on that object.

    0 讨论(0)
提交回复
热议问题