ruby 如何将文本文件读入数组数组(每个子数组都是文本文件中的一行?)
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/17883896/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How do I read a text file into an array of array (each sub-array being a row in the text file?)
提问by Howzlife17
so I'm pretty much a n00b at Ruby, and I've put together a code to solve a MinCut problem (for an assignment, yes - that part of the code I've put together and tested), and I can't figure out how to read a file and put it into an array of arrays. I have a text file to read, with columns of varying length as below
所以我几乎是 Ruby 的 n00b,我已经整理了一个代码来解决 MinCut 问题(对于一个作业,是的 - 我已经整理和测试的那部分代码),但我不能弄清楚如何读取文件并将其放入数组数组中。我有一个文本文件要阅读,列的长度不同,如下所示
1 37 79 164
2 123 134
3 48 123 134 109
1 37 79 164
2 123 134
3 48 123 134 109
and I'd like to read it into a 2D array, where each line and columnn is split, with each line going into one array. So the resulting array for the above example would be :
我想将它读入一个二维数组,其中每一行和列都被拆分,每一行都进入一个数组。因此,上述示例的结果数组将是:
[[1, 37, 79, 164], [2, 123, 134], [3, 48, 123, 134, 109]]
My code to read the text file is below:
我读取文本文件的代码如下:
def read_array(file, count)
int_array = []
File.foreach(file) do |f|
counter = 0
while (l = f.gets and counter < count ) do
temp_array = []
temp_array << l.to_i.split(" ")
int_array << temp_array
counter = counter + 1
end
end
return int_array
end
Any help is greatly appreciated!
任何帮助是极大的赞赏!
Also, if it helps, the error I'm currently getting is "block in read_array': private method 'gets' called for # "
另外,如果有帮助,我目前得到的错误是“block in read_array': private method 'gets' call for #”
I've tried a few things, and have gotten different error messages though...
我已经尝试了几件事,但收到了不同的错误消息......
回答by tessi
File.readlines('test.txt').map do |line|
line.split.map(&:to_i)
end
Explanation
解释
readlinesreads the whole file and splits it by newlines. It looks like this:
readlines读取整个文件并用换行符分割它。它看起来像这样:
["1 37 79 164\n", "2 123 134\n", "3 48 123 134 109"]
Now we iterate over the lines (using map) and split each line into its number parts (split)
现在我们迭代这些行(使用map)并将每一行分成它的编号部分(split)
[["1", "37", "79", "164"], ["2", "123", "134"], ["3", "48", "123", "134", "109"]]
The items are still strings, so the inner mapconverts them to integers (to_i).
项目仍然是字符串,因此内部map将它们转换为整数 ( to_i)。
[[1, 37, 79, 164], [2, 123, 134], [3, 48, 123, 134, 109]]
回答by Chowlett
Ruby's got you covered with just a few lines:
Ruby 只用几行代码就可以帮你搞定:
tmp.txt
文件.txt
1 2 3
10 20 30 45
4 2
Ruby code
红宝石代码
a = []
File.open('tmp.txt') do |f|
f.lines.each do |line|
a << line.split.map(&:to_i)
end
end
puts a.inspect
# => [[1, 2, 3], [10, 20, 30, 45], [4, 2]]
回答by toro2k
The error in your code occurs because you are calling the method getson the object f, which is a String, not a Fileas you would expected (check the documentation for IO#foreachfor more informations).
代码中的错误是因为您正在调用getsobject 上的方法f,它是 a String,而不是File您预期的 a (查看文档以IO#foreach获取更多信息)。
Instead of fixing your code I suggest you to rewrite it in a simpler and more Rubyish style, I'd write it like this:
与其修复你的代码,我建议你用更简单、更像 Rubyish 的风格重写它,我会这样写:
def read_array(file_path)
File.foreach(file_path).with_object([]) do |line, result|
result << line.split.map(&:to_i)
end
end
Given this file.txt:
鉴于此file.txt:
1 37 79 164
2 123 134
3 48 123 134 109
It produce this output:
它产生这个输出:
read_array('file.txt')
# => [[1, 37, 79, 164], [2, 123, 134], [3, 48, 123, 134, 109]]
回答by Reza
array_line = []
if File.exist? 'test.txt'
File.foreach( 'test.txt' ) do |line|
array_line.push line
end
end
回答by lurker
def read_array(file)
int_array = []
File.open(file, "r").each_line { |line| int_array << line.split(' ').map {|c| c.to_i} }
int_array
end

