如何解析文本文件
name id
name id
并保存在 ruby 中的数组数组中。
到目前为止,我有:
content = []
File.open("my/file/path", "r").each_line do |line|
person << line.chop
end
它给出的输出为:
"name\tID", "name2\tID" ....
如何解析文本文件
name id
name id
并保存在 ruby 中的数组数组中。
到目前为止,我有:
content = []
File.open("my/file/path", "r").each_line do |line|
person << line.chop
end
它给出的输出为:
"name\tID", "name2\tID" ....
这是我解决这个问题的方法:
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
使用 ruby 的字符串#split
pry(main)> "foo\tbar".split("\t")
=> ["foo", "bar"]
这应该工作:
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