Jim Freeze graced us by uttering:
> On Thu, May 09, 2002 at 06:59:10AM +0900, Tim Hammerquist wrote:
>> Jim Freeze graced us by uttering:
>> 
>> $ cat filter.rb
>> #!/usr/local/bin/ruby -w
>> 
>> while gets
>>   # each line given in $_ for each iteration
>>   puts "you gave me: #$_"
>> end
> 
> Close, but I am looking for something without the
> while and gets statements. Something more like readlines.
> 
> Here is my meager attempt:
> 
> cat pipe.rb 
> #! /usr/local/bin/ruby
> 
> if 1 == ARGV.size
>   lines = IO.readlines(ARGV[0])
> else
>   lines = $stdin.read.split(/\n/)
> end
> 
> p lines

Very well. To slurp an entire file into memory all at once, just use the
IO#read or IO#readlines methods.

  lines = $stdin.readlines

or

  lines = $<.readlines

Take care when slurping whole files; it can be terribly (or fatally)
inefficient if dealing with large files. DON'T SLURP IF YOU'LL BE
DEALING WITH VERY LARGE FILES!

If you want to strip the newlines on each line, you can try:

  lines = file.readlines.collect { |line| line.chomp }

or

  lines = file.readlines.collect { |$_| chomp }

The gets/$_ loop I showed in a previous post does much of your if/else
logic internally, using the implied IO object $<. If there are any
elements left in ARGV, it treats them as filenames to be opened and
read from. Otherwise, it reads from $stdin.  This feature is based on
Perl's <> ('diamond') operator.  For example:

$ cat pipe.rb
#!/usr/local/bin/ruby -w

lines = $<.readlines

p lines
$ grep '.' file{1,2,3}.txt
file1.txt:one
file2.txt:two
file3.txt:three
$ pipe.rb file{1,2,3}.txt
["one\n", "two\n", "three\n"]
$ cat file{1,2,3}.txt | pipe.rb
["one\n", "two\n", "three\n"]
$ cat file3.txt | pipe.rb file{1,2}.txt
["one\n", "two\n"]
$

The downfall being if you only want to read _one_ file on the command
line, as your code shows.  My understanding of this is, strip all
elements of ARGV that you don't want read as input _before_ calling a
method on $<.

Tim Hammerquist
-- 
I think that's easier to read.  Pardon me.  Less difficult to read.
    -- Larry Wall in <199710120226.TAA06867 / wall.org>