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

标签 ruby arrays methods

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

#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/

相关文章:

ruby - JSON.parse 抛出 Encoding::UndefinedConversionError

ruby - 未定义方法 `%' 对于 nil :NilClass

arrays - 将文本保存在数组中并显示在表格 View 中

c - 如何结束遍历指针数组的 for 循环

c - 循环内循环 - 我快到了,但这段代码只是稍微偏离

c# - 为什么这两个方法没有歧义呢?

r - 在 R 中,如何在另一个包中的类上设置通用方法?

ruby - 置换的递归解

ruby-on-rails - gmail 阻止 Rails 应用程序发送电子邮件

scala - Foo在Scala中不带参数编译错误?