Script to run against stdin if no arg; otherwise i

2019-02-07 03:09发布

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

3条回答
男人必须洒脱
2楼-- · 2019-02-07 03:32

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

input = ARGV ? $< : File.new(ARGV[0])
查看更多
走好不送
3楼-- · 2019-02-07 03:47

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 $<.read

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

while s = gets
  puts s
end
查看更多
兄弟一词,经得起流年.
4楼-- · 2019-02-07 03:49

then and ; are optional

also you can use the ternary operator:

input = ARGV[0].nil? ? $< : File.new(ARGV[0],"r")
查看更多
登录 后发表回答