English 中文(简体)
B. 铁路的有限档案区
原标题:Tab delimited file parsing in Rails

我有这样的档案。

ID Name  Car
1  Mike  Honda
2  Adam  Jim

These values are tab delimited, and from this I want to parse it in Ruby and put it into my database.

我已尝试如下:

require  csv 

CSV.foreach("public/files/example.tab", {:col_sep => "	"}) do |row|
  @stuff = row[0]
end

@stuff 只是归还整个物体,似乎没有使用第1栏所列分离器。

它也没有考虑到第一行是头盔。

我怎么能够把一个被制成的档案划归Ruu,我如何告诉它第一行是头盔?

最佳回答

我成功地利用了FerCSV和Rub.1.8.7,我认为它现在成为1.9个核心图书馆:

table = FasterCSV.read(result_file.to_file.path, { :headers => true, :col_sep => "	", :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
问题回答

我用简单的方式来分类数据。 这里的划界者是表、空间、 com或半殖民地。 它返回了各个领域。

row_data = File.new("your_file.csv").read

row_data = row_data.split(/[ ,;s]/).reject(&:empty?)




相关问题
Styling rows in table that uses CSV data through PHP

I ve been working on this simple code that puts a CSV file into a nice table. But because the data is imported, styling ODD rows is a pretty hard thing to do. All I need would be a method to address ...

PHP - Sanitise a comma separated string

What would be the most efficient way to clean a user input that is a comma separated string made entirely on numbers - e.g 2,40,23,11,55 I use this function on a lot of my inputs function clean($...

marking duplicates in a csv file

I m stumped with a problem illustrated in the sample below: "ID","NAME","PHONE","REF","DISCARD" 1,"JOHN",12345,, 2,"PETER",6232,, 3,"JON",12345,, 4,"PETERSON",6232,, 5,"ALEX",7854,, 6,"JON",12345,, ...

Interactive heat map in Flex

I’m at a very basic level with Flex and with programming in general. I am working on a project where I have data in an Excel (.csv) format, it’s a large Excel plot/matrix where each cell has a ...

热门标签