如果没有参数,则针对标准输入运行的脚本;否则输入文件=ARGV[0]

发布于 2024-08-16 23:28:59 字数 239 浏览 3 评论 0原文

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

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

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

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

...
# Do something with the input here, for example:
input.each_line do |line|
    puts line
end

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(3

暖心男生 2024-08-23 23:28:59

您可以完全删除前五行。

来自镐

$<:提供访问的对象
内容的串联
作为命令行给出的所有文件
参数或 $stdin (在这种情况下
没有争论)。 $<支持
与 File 对象类似的方法:
binmode,关闭,关闭?,每个,
每个_字节,每个_行,eof,eof?,文件,
文件名、文件号、getc、获取、行号、
lineno=,路径,pos,pos=,读取,
readchar、readline、readlines、倒带、
寻找、跳过、告诉、to_a、to_i、to_io、
to_s,以及中的方法
可数。该方法文件返回一个
当前文件的文件对象
正在阅读。这可能会改变为 $<
通过命令读取文件
线。 [读/写]

因此:

print 
lt;.read

Kernel.gets 是 $<.gets 的简写,因此:

while s = gets
  puts s
end

You can eliminate the first five lines entirely.

From 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]

Therefore:

print 
lt;.read

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

while s = gets
  puts s
end
赤濁 2024-08-23 23:28:59

只有 ARGV ? 对我有用,"r" 通常是默认的,所以可以跳过它,File.new() 可能与 相同>文件(),所以

input = ARGV ? 
lt; : File.new(ARGV[0])

Only ARGV ? works for me, "r" normally default so can skip it, and File.new() may be same to File(), So

input = ARGV ? 
lt; : File.new(ARGV[0])
从﹋此江山别 2024-08-23 23:28:59

then; 是可选的

,您也可以使用三元运算符:

input = ARGV[0].nil? ? 
lt; : File.new(ARGV[0],"r")

then and ; are optional

also you can use the ternary operator:

input = ARGV[0].nil? ? 
lt; : File.new(ARGV[0],"r")
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文