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?
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?
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With