Script to run against stdin if no arg; otherwise, the input file = ARGV [0]

This works pretty well - just wondering if there are any improvements to cut 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 
+7
idioms ruby file stdin
source share
3 answers

You can completely exclude the first five lines.

From Pickaxe

$ <: An object that provides access to concatenate the contents of all files specified on the command line of arguments or $ stdin (in the case when there are no arguments). $ & L; supports methods similar to the 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, search, skip, tell, to_a, to_i, to_io, to_s, as well as methods in Enumerated. The method file returns the file object for the file that is currently being read. This may change as $ <reads files on command line. [G / o]

Thus:

 print $<.read 

Kernel.gets is short for $ <. Gets, therefore:

 while s = gets puts s end 
+18
source share

Only ARGV ? works for me, "r" usually the default, so it may skip it, and File.new() may be the same as File() , So

 input = ARGV ? $< : File.new(ARGV[0]) 
+3
source share

then and ; are optional

also you can use the ternary operator:

 input = ARGV[0].nil? ? $< : File.new(ARGV[0],"r") 
+2
source share

All Articles