加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 百科 > 正文

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

发布时间:2020-12-17 04:36:16 所属栏目:百科 来源:网络整理
导读:这很好用 – 只是想知道是否有任何改进来缩短它? 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 lineend 解决方法 你可以完全消除前五行. 来自Pi
这很好用 – 只是想知道是否有任何改进来缩短它?
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

解决方法

你可以完全消除前五行.

来自Pickaxe

$<: 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的简写,所以:

while s = gets
  puts s
end

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读