Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to convert STDIN contents to an array?

Tags:

arrays

ruby

stdin

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?

like image 294
miketaylr Avatar asked Feb 14 '09 03:02

miketaylr


2 Answers

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>

like image 79
womble Avatar answered Oct 24 '22 19:10

womble


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>"
like image 1
manveru Avatar answered Oct 24 '22 18:10

manveru