gpt4 book ai didi

Ruby 新手 : Writing a method to read mulitple arrays from a file?

转载 作者:数据小太阳 更新时间:2023-10-29 08:49:45 24 4
gpt4 key购买 nike

我有一个文件,其中有十个单独的数据列,用空格分隔。我已经编写了以下代码(并且有效),但我觉得有一种更简洁的方法来完成我在这里所做的事情:

#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

其中每一列都是一个Hash,有一个按行索引的部分,所有的行都存储在一个数组中

关于Ruby 新手 : Writing a method to read mulitple arrays from a file?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16049755/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com