在Rails中使用制表符分隔文件解析

Mik*_*vis 10 csv ruby-on-rails-3

我有一个看起来像这样的文件

ID Name  Car
1  Mike  Honda
2  Adam  Jim
Run Code Online (Sandbox Code Playgroud)

这些值是制表符分隔的,从中我想在Ruby中解析它并将其放入我的数据库中.

我尝试了以下内容

require 'csv'

CSV.foreach("public/files/example.tab", {:col_sep => "\t"}) do |row|
  @stuff = row[0]
end
Run Code Online (Sandbox Code Playgroud)

@stuff只返回整个对象,似乎没有使用我指定的列分隔符.

它也没有考虑第一行是标题.

如何在Ruby中解析制表符分隔文件,如何告诉它第一行是标题?

use*_*725 4

我在 FasterCSV 和 Ruby 1.8.7 上取得了成功,我相信它现在是 1.9 中的核心 csv 库,使用这个:

table = FasterCSV.read(result_file.to_file.path, { :headers => true, :col_sep => "\t", :skip_blanks => true })
unless table.empty?
    header_arry = Array.new
    table.headers.each do |h|
      #your header logic, e.g.
      # if h.downcase.include? 'pos'
        # header_arry << 'position'
      # end
      # simplest case here
      header_arry << h.downcase
      #which produces an array of column names called header_arry
    end

    rows = table.to_a
    rows.delete_at(0)
    rows.each do |row|
      #convert to hash using the column names
      hash = Hash[header_arry.zip(row)]
      # do something with the row hash
    end
  end
Run Code Online (Sandbox Code Playgroud)