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

时间:2010-01-06 14:07:35

标签: ruby file stdin idioms

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

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

3 个答案:

答案 0 :(得分:18)

你可以完全消除前五行。

来自Pickaxe

  

$&lt;:提供访问权限的对象   连贯的内容   作为命令行给出的所有文件   参数或$ stdin(在这种情况下   没有争论)。 $&LT;支持   类似于File对象的方法:   binmode,关闭,关闭?,每个,   each_byte,each_line,eof,eof?,file,   filename,fileno,getc,gets,lineno,   lineno =,path,pos,pos =,read,   readchar,readline,readlines,rewind,   寻找,跳过,告诉,to_a,to_i,to_io,   to_s,以及中的方法   枚举。方法文件返回一个   当前文件的文件对象   正在阅读这可能会改变为$&lt;   读取命令中的文件   线。 [R / O]

因此:

print $<.read

Kernel.gets是$&lt; .gets的缩写,所以:

while s = gets
  puts s
end

答案 1 :(得分:3)

只有ARGV ?适用于我,"r"通常是默认值,因此可以跳过它,File.new()可能与File()相同,所以

input = ARGV ? $< : File.new(ARGV[0])

答案 2 :(得分:2)

then;是可选的

你也可以使用三元运算符:

input = ARGV[0].nil? ? $< : File.new(ARGV[0],"r")
相关问题