Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I read line by line a text file in ruby (hosting it on s3)?

I know I've done this before and found a simple set of code, but I cannot remember or find it :(.

I have a text file of records I want to import into my Rails 3 application.

Each line represents a record. Potentially it may be tab delimited for the attributes, but am fine with just a single value as well.

How do I do this?

like image 373
Satchel Avatar asked Apr 27 '11 18:04

Satchel


Video Answer


2 Answers

File.open("my/file/path", "r").each_line do |line|   # name: "Angela"    job: "Writer"    ...   data = line.split(/\t/)   name, job = data.map{|d| d.split(": ")[1] }.flatten end 

Related topic

What are all the common ways to read a file in Ruby?

like image 163
fl00r Avatar answered Sep 18 '22 19:09

fl00r


You want IO.foreach:

IO.foreach('foo.txt') do |line|   # process the line of text here end 

Alternatively, if it really is tab-delimited, you might want to use the CSV library:

File.open('foo.txt') do |f|   CSV.foreach(f, col_sep:"\t") do |csv_row|     # All parsed for you   end end 
like image 26
Phrogz Avatar answered Sep 21 '22 19:09

Phrogz