如果没有arg,则针对stdin运行脚本;否则输入文件= ARGV [0] [英] Script to run against stdin if no arg; otherwise input file =ARGV[0]

查看:89
本文介绍了如果没有arg,则针对stdin运行脚本;否则输入文件= ARGV [0]的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

This works quite nicely - just wondered if there are any improvements to shorten it ?

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

推荐答案

您可以完全消除前五行.

You can eliminate the first five lines entirely.

来自镐头

$< ;:提供访问以下内容的对象 内容的串联 以命令行形式给出的所有文件 参数或$ stdin(如果 没有参数). $<支持 与File对象类似的方法: binmode,close,closed ?,每个, each_byte,each_line,eof,eof ?、文件, 文件名,fileno,getc,gets,lineno, lineno =,路径,pos,pos =,读取, readchar,readline,readlines,倒带, 搜寻,跳过,告诉,to_a,to_i,to_io, to_s,以及中的方法 可数.方法文件返回一个 当前文件的文件对象 被阅读.这可能会更改为$< 读取命令上的文件 线. [r/o]

$<: An object that provides access to the concatenation of the contents of all the files given as command-line arguments or $stdin (in the case where there are no arguments). $< supports methods similar to a File object: 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, along with the methods in Enumerable. The method file returns a File object for the file currently being read. This may change as $< reads through the files on the command line. [r/o]

因此:

print $<.read

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

Kernel.gets is shorthand for $<.gets, so:

while s = gets
  puts s
end

这篇关于如果没有arg,则针对stdin运行脚本;否则输入文件= ARGV [0]的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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