How to convert STDIN contents to an array?

左心房为你撑大大i 提交于 2019-12-05 22:55:49

问题


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?


回答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>




回答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>"



回答3:


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



来源:https://stackoverflow.com/questions/548446/how-to-convert-stdin-contents-to-an-array

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!