How to convert STDIN contents to an array?

12,736

Solution 1

You want

myArray = $stdin.readlines

That'll get all of $stdin into an array with one array entry per line of input.

Note that this is spectacularly inefficient (memory wise) with large input files, so you're far better off using something like:

$stdin.each_line do |l|
  ...
end

instead of

a = $stdin.readlines
a.each do |l|
  ...
end

Because the former doesn't allocate memory for everything up-front. Try processing a multi-gigabyte log file the second way to see just how good your system's swap performance is... <grin>

Solution 2

What your are after is using $stdin instead of $stdin.to_s

ruby -e 'p $stdin.readlines.size' < INPUT
3

ruby -e 'p $stdin.to_s'
"#<IO:0x7fc7cc578af0>"

Solution 3

STDIN.lines is lazy, but gives you an array-like structure to pass around and iterate over.

Share:
12,736
miketaylr
Author by

miketaylr

Updated on July 28, 2022

Comments

  • miketaylr
    miketaylr almost 2 years

    I've got a file INPUT that has the following contents:

    123\n
    456\n
    789
    

    I want to run my script like so: script.rb < INPUT and have it convert the contents of the INPUT file to an array, splitting on the new line character. So, I'd having something like myArray = [123,456,789]. Here's what I've tried to do and am not having much luck:

    myArray = STDIN.to_s
    myArray.split(/\n/)
    puts field.size
    

    I'm expecting this to print 3, but I'm getting 15. I'm really confused here. Any pointers?