How to convert STDIN contents to an array? How to convert STDIN contents to an array? ruby ruby

How to convert STDIN contents to an array?


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.readlinesa.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>


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

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


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