如何将STDIN内容转换为数组? [英] How to convert STDIN contents to an array?
问题描述
我有一个具有以下内容的文件输入:
I've got a file INPUT that has the following contents:
123\n
456\n
789
我想像这样运行我的脚本:script.rb< INPUT并使其将INPUT文件的内容转换为数组,并在换行符上进行拆分.所以,我会有类似myArray = [123,456,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
我希望它能打印3,但我要打印15.我真的很困惑.有指针吗?
I'm expecting this to print 3, but I'm getting 15. I'm really confused here. Any pointers?
推荐答案
您想要的
myArray = $stdin.readlines
这将把所有$ stdin都放入一个数组,每行输入只有一个数组项.
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
代替
a = $stdin.readlines
a.each do |l|
...
end
因为前者并没有为所有事情分配内存.尝试以第二种方式处理一个数千兆字节的日志文件,以查看您的系统的交换性能如何……< grin>
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>
这篇关于如何将STDIN内容转换为数组?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!