为什么在将参数传递给我的 ruby​​ 脚本时会抛出错误? [英] Why is gets throwing an error when arguments are passed to my ruby script?

查看:47
本文介绍了为什么在将参数传递给我的 ruby​​ 脚本时会抛出错误?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用 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'
    ...

错误消息显示了我传递给脚本的参数.为什么会关注 ARGV?

The error message is showing the argument I passed to the script. Why would gets be looking at ARGV?

我正在使用 OptionParser 来解析我的命令行参数.如果我使用 parse! 而不是 parse(因此它会从参数列表中删除它解析的内容),那么应用程序工作正常.

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.

所以看起来 get 出于某种原因正在从 ARGV 读取.为什么?这是预期的吗?有没有办法让它不这样做(做 gets() 没有帮助).

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).

推荐答案

Ruby 会自动将未解析的参数视为文件名,然后打开并读取文件,使输入可用于 ARGF ($<).默认情况下,gets 从 ARGF 读取.绕过那个:

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

有人建议您可以使用 STDIN 而不是 $stdin,但通常是 最好使用 $stdin.

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

此外,在您从 ARGV 捕获您想要的输入后,您可以使用:

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

ARGV.clear

然后您就可以自由地gets,而无需从您可能不打算读取的文件中读取.

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

这篇关于为什么在将参数传递给我的 ruby​​ 脚本时会抛出错误?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆