当参数传递给我的 ruby 脚本时,为什么会抛出错误?
我使用 gets
暂停脚本的输出,直到用户按下 Enter 键。如果我不向脚本传递任何参数,那么它就可以正常工作。但是,如果我将任何参数传递给脚本,则会因以下错误而死亡:
ruby main.rb -i
main.rb:74:in `gets': No such file or directory - -i (Errno::ENOENT)
from main.rb:74:in `gets'
...
错误消息显示我传递给脚本的参数。为什么人们会关注 ARGV?
我正在使用 OptionParser 来解析我的命令行参数。如果我使用 parse!
而不是 parse
(这样它会从参数列表中删除它解析的内容),那么应用程序就可以正常工作。
所以看起来 gets 出于某种原因正在从 ARGV 读取数据。为什么?这是预期的吗?有没有办法让它不这样做(做 gets()
没有帮助)。
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 pass any arguments to my script then gets dies with the following error:
ruby main.rb -i
main.rb:74:in `gets': No such file or directory - -i (Errno::ENOENT)
from main.rb:74:in `gets'
...
The error message is showing the argument I passed to the script. Why would gets be looking at ARGV?
I'm using OptionParser to parse my command line arguments. If I use parse!
instead of parse
(so it removes things it parses from the argument list) then the application works fine.
So it looks like gets is reading from ARGV for some reason. Why? Is this expected? Is there a way to get it to not do that (doing gets()
didn't help).
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
Ruby 会自动将未解析的参数视为文件名,然后打开并读取文件,使输入可用于
ARGF
($<
)。默认情况下,get
从 ARGF 读取。要绕过这个问题:建议您可以使用
STDIN
而不是$stdin
,但通常是 最好使用$stdin
。此外,在从
ARGV
捕获所需的输入后,您可以使用:然后您就可以自由地
gets
而无需从您可能不打算读取的文件中读取。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: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:Then you'll be free to
gets
without it reading from files you may not have intended to read.Kernel#gets 的要点是将传递给程序的参数视为文件名并读取这些文件。 文档中的第一句话是:
这就是
gets
的工作原理。如果您想读取特定IO
对象(例如$stdin
),只需调用gets
即可目的。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:That's just how
gets
works. If you want to read from a specificIO
object (say,$stdin
), just callgets
on that object.