のようなテキストファイルを解析する方法
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 のString#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