-2

如何解析文本文件

name   id
name   id

并保存在 ruby​​ 中的数组数组中。

到目前为止,我有:

content = []
File.open("my/file/path", "r").each_line do |line|
    person << line.chop
end

它给出的输出为:

"name\tID", "name2\tID" ....
4

3 回答 3

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
于 2013-01-11T23:52:02.063 回答
2

使用 ruby​​ 的字符串#split

pry(main)> "foo\tbar".split("\t")
=> ["foo", "bar"]
于 2013-01-11T23:49:27.140 回答
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
于 2013-01-11T23:50:02.983 回答