如果没有arg,则运行stdin的脚本; 否则输入文件= ARGV [0]

mon*_*nny 7 ruby stdin idioms file

这很好用 - 只是想知道是否有任何改进来缩短它?

if (ARGV[0].nil?) then
    input=$<
else
    input=File.new(ARGV[0],"r");
end

...
# Do something with the input here, for example:
input.each_line do |line|
    puts line
end
Run Code Online (Sandbox Code Playgroud)

Way*_*rad 18

你可以完全消除前五行.

来自Pickaxe

$ <:一个对象,它提供对作为命令行参数或$ stdin(在没有参数的情况下)给出的所有文件内容的连接的访问​​.$ <支持类似于File对象的方法:binmode,close,closed?,each,each_byte,each_line,eof,eof?,file,filename,fileno,getc,gets,lineno,lineno =,path,pos,pos =, read,readchar,readline,readlines,rewind,seek,skip,tell,to_a,to_i,to_io,to_s,以及Enumerable中的方法.方法文件返回当前正在读取的文件的File对象.这可能会随着$ <读取命令行中的文件而改变.[R/O]

因此:

print $<.read
Run Code Online (Sandbox Code Playgroud)

Kernel.gets是$ <.gets的简写,所以:

while s = gets
  puts s
end
Run Code Online (Sandbox Code Playgroud)

  • 此外,您可以使用`ARGF`,因为它是`$ <`的别名. (2认同)