本文介绍了Kernel#gets 尝试读取文件而不是标准输入的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我对 Ruby 比较陌生,今天我编写了一个应用程序,您可以通过 ARGV 将参数传递给它.但是在我的应用程序中,我希望能够使用gets".问题是,每次我尝试这样做时,都会出错.

I'm rather new to Ruby, and today I wrote an application which you can pass arguments to via ARGV. But inside my application, I want to be able to use "gets". Problem is, every time I try to do so, I get an error.

这是一个简单的脚本,显示了我的问题:

Here's a simple script which shows my problem:

print "Say something! "
input = gets

如果我这样称呼它:

$ ruby script.rb this is arguments

我收到此错误:

script.rb:2:in `gets': No such file or directory - this (Errno::ENOENT)
from script.rb:2

希望有人能帮我解决这个问题,这样我就可以继续我的 Ruby 之旅了.:)

Hope someone is able to help me solve this, so I can continue my Ruby journey. :)

我知道Gets"不会检索传递给文件的参数.Gets"将查询用户的输入.我希望能够在我的应用程序中使用这两种方法.

I am aware that "Gets" won't retrieve arguments passed to the file. "Gets" will query the user for input. I want to be able to use both these methods inside my application.

推荐答案

如果有参数,默认的 gets 方法会尝试将第一个参数视为文件并从中读取.在这种情况下要从 $stdin 中读取,你必须明确使用它:

If there are arguments, the default gets method tries to treat the first one as a file and read from that. To read from $stdin in such a situation, you have to use it explicitly:

print "Say something! "
input = $stdin.gets

这篇关于Kernel#gets 尝试读取文件而不是标准输入的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

10-29 06:45