如何解析文本文件,如
name id
name id
并保存在ruby中的数组数组中。
到目前为止,我有:
content = []
File.open("my/file/path", "r").each_line do |line|
person << line.chop
end
它将输出显示为:
"name\tID", "name2\tID" ....
答案 0 :(得分:4)
以下是我如何解决这个问题:
class Person
attr :name, :id
def initialize(name, id)
@name, @id = name.strip, id.strip
end
end
class << Person
attr_accessor :file, :separator
def all
Array.new.tap do |persons|
File.foreach file do |line|
persons.push new *line.split(separator)
end
end
end
end
Person.file = 'my/file/path'
Person.separator = /\t/
persons = Person.all
persons.each do |person|
puts "#{person.id} => #{person.name}"
end
答案 1 :(得分:2)
使用ruby的String#split
pry(main)> "foo\tbar".split("\t")
=> ["foo", "bar"]
答案 2 :(得分:0)
这应该有效:
content = []
File.open("my/file/path", "r").each_line do |line|
person << line.chop.split("\t")
end
编辑:要创建单独的数组,请执行以下操作:
content = []
persons = []
ids = []
File.open("my/file/path", "r").each_line do |line|
temp = line.chop.split("\t")
persons << temp[0]
ids << temp[1]
end