我有一个文件,其中包含由空格分隔的十个独立数据列。我编写了以下代码(并且它有效),但我觉得有一种更简洁的方法可以完成我在这里所做的事情:
#Generate ten separate arrays in which to store the columns
c0 = []; c1 = []; c2 = []; c3 = []; c4 = [];
c5 = []; c6 = []; c7 = []; c8 = []; c9 = [];
#Append each item in each line to its own array
File.open(filename, 'r').each_line do |line|
line = line.strip.split(' ')
c0 << line[0]; c1 << line[1]; c2 << line[2]; c3 << line[3]; c4 << line[4];
c5 << line[5]; c6 << line[6]; c7 << line[7]; c8 << line[8]; c9 << line[9];
end
我尝试编写一种方法来完成此任务,但我基本上不知道从哪里开始。我想有一种比我所做的更干净的方法来初始化 n 个数组......这样做的“ruby”方法是什么?是否可以用一个返回 10 个数组的方法来完成我在这里所做的一切?关于如何实现这一点的帮助/提示将不胜感激。
最佳答案
也许这段代码有帮助:
c = []
File.open(filename, 'r').each_line do |line|
line = line.strip.split(' ')
columns = Hash.new
index=0
line.each do |column|
columns[index] = column
index+=1
end
c.push(columns)
end
其中每一列都是一个哈希,其中按行部分有索引,所有行都存储在一个数组中
关于Ruby新手: Writing a method to read mulitple arrays from a file?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16049755/