【问题标题】:How do I read in a text file (containing comma separated numbers) into a list of integers in Ruby? [closed]如何将文本文件(包含逗号分隔的数字)读入 Ruby 中的整数列表? [关闭]
【发布时间】:2021-01-13 16:10:37
【问题描述】:

我有一个包含如下数字的文本文件:

1,1,4,3,3,4,2,2,1,2,2,3,1,2,2,2,3,4,2,3,3,3,2,3,3,1,3,3,3,3,3

在我的代码中,我需要遍历一个整数数组并逐个读取它们以对它们执行数字运算。有点像这样:

  dna.each { |a|
    d = dna[a]
    dl << d #adjust dice total as rand_i=>0-5 so add 1 to each dice score
    cl << w[d][i] #add looked up bar number to list
  }
end

其中 DNA 是一个列表,即:dna = [1, 2, 4, 3, 2, 4, 3, 2, 4]

但是,当我尝试将其转换为列表时(基于 Stackoverflow 上的其他答案),总是有一个尾随空格,如 3\n,我无法再将其作为整数处理。这是我以前逐行阅读的内容(因为可以将文本文件修改为每行一个数字):

File.readlines("a.txt")

但正如我所说,这会将\n 字符附加到项目,不能再将其作为整数处理。

如何确保将文件传递到整数数组中,以便通过索引访问其元素?

【问题讨论】:

  • 读取行后替换空格和换行符然后使用 split 并转换为 int

标签: arrays ruby list text


【解决方案1】:

读取文件,去掉换行符,用逗号分隔并将元素转换为整数:

File.read("a.txt").strip.split(',').map(&:to_i)

【讨论】:

    猜你喜欢
    • 2023-03-15
    • 1970-01-01
    • 2016-08-19
    • 1970-01-01
    • 1970-01-01
    • 2021-05-24
    • 1970-01-01
    • 1970-01-01
    • 2020-10-23
    相关资源
    最近更新 更多