有一点,我想将一些信息存储在一个文件中并以这样的方式从中读取,最后我有一个二维数组。
假设这是配置文件的内容:
Banana:Yellow
Apple:Red
这是我想出的代码:
a = File.read("config.txt")
b = a.split("\n")
k = Array.new
b.each { |x| k.push(x.split(":"))}
print k
它有效,但肯定有更好的方法来做到这一点?
最佳答案
您可以使用 IO::readlines
执行以下操作和 String#splt
File.readlines("config.txt").map { |str| str.split(":") }
或者,使用 CSV::read
require 'csv'
CSV.read("path/to/file", 'rb', :col_sep => ':')
# => [["Banana", "Yellow"], ["Apple", "Red"]]
使用 CSV,您可以跳过行,您不想使用选项 :skip_lines
处理:
When set to an object responding to match, every line matching it is considered a comment and ignored during parsing. When set to a String, it is first converted to a Regexp. When set to nil no line is considered a comment. If the passed object does not respond to match, ArgumentError is thrown.
假设我有一个文件test.txt
,内容为:-
Banana:Yellow
Apple:Reds
#foo:biz
bar:cz
现在我不想阅读以 #
开头的行。然后我将代码重写为
require 'csv'
CSV.read("#{__dir__}/test.txt", 'rb', :col_sep => ':',:skip_lines => /\A#/)
让我们运行代码,看看它做了什么:
arup@linux-wzza:~/Ruby> ruby test.rb
[["Banana", "Yellow"], ["Apple", "Reds"], ["bar", "cz"]]
arup@linux-wzza:~/Ruby>
关于Ruby:如何将从文件中读取的行拆分为二维数组?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24289501/