-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 のString#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 に答える