Ruby 将第一个命令行参数视为标准输入
Ruby treats first command-line args as stdin
运行 带有命令行参数的 Ruby 脚本使 $stdin
从第一个命令行参数而不是从 tty 读取。
echo "puts gets" > myscript.rb
ruby myscript.rb foo
# myscript.rb:1:in `gets': No such file or directory @ rb_sysopen - foo (Errno::ENOENT)
在这个例子中,我想在 tty 上编写询问我输入的脚本,然后回显我提供的任何输入,但是 Ruby 查找名为 foo
的文件并尝试从中读取。
我如何提供命令行参数,但仍然 Ruby 提示我在 tty 上输入?
引用自the documentation of Kernel#gets
(强调我的):
Returns (and assigns to $_
) the next line from the list of files in ARGV
(or $*
), or from standard input if no files are present on the command line. Returns nil
at end of file. The optional argument specifies the record separator. The separator is included with the contents of each record. A separator of nil
reads the entire contents, and a zero-length separator reads the input one paragraph at a time, where paragraphs are divided by two consecutive newlines. If the first argument is an integer, or optional second argument is given, the returning string would not be longer than the given value in bytes. If multiple filenames are present in ARGV
, gets(nil)
will read the contents one file at a time.
因此,gets
returns 文件名中的行作为参数传递给当前程序。如果 ARGV
.
中没有进一步的命令行参数,它只会使用 STDIN
您可以不使用 Kernel#gets
而改写此行为 IO#gets
:
echo 'puts $stdin.gets' > myscript.rb
ruby myscript.rb foo
运行 带有命令行参数的 Ruby 脚本使 $stdin
从第一个命令行参数而不是从 tty 读取。
echo "puts gets" > myscript.rb
ruby myscript.rb foo
# myscript.rb:1:in `gets': No such file or directory @ rb_sysopen - foo (Errno::ENOENT)
在这个例子中,我想在 tty 上编写询问我输入的脚本,然后回显我提供的任何输入,但是 Ruby 查找名为 foo
的文件并尝试从中读取。
我如何提供命令行参数,但仍然 Ruby 提示我在 tty 上输入?
引用自the documentation of Kernel#gets
(强调我的):
Returns (and assigns to
$_
) the next line from the list of files inARGV
(or$*
), or from standard input if no files are present on the command line. Returnsnil
at end of file. The optional argument specifies the record separator. The separator is included with the contents of each record. A separator ofnil
reads the entire contents, and a zero-length separator reads the input one paragraph at a time, where paragraphs are divided by two consecutive newlines. If the first argument is an integer, or optional second argument is given, the returning string would not be longer than the given value in bytes. If multiple filenames are present inARGV
,gets(nil)
will read the contents one file at a time.
因此,gets
returns 文件名中的行作为参数传递给当前程序。如果 ARGV
.
您可以不使用 Kernel#gets
而改写此行为 IO#gets
:
echo 'puts $stdin.gets' > myscript.rb
ruby myscript.rb foo