Domanda

I have the following code:

  def csv_to_array(file)
    csv = CSV::parse(file)
    fields = csv.shift
    array = csv.collect { |record| Hash[*fields.zip(record).flatten] }
  end

This creates an array of hashes, and works fine with comma separated values. I am trying to replicate this code for a tab delimited file. Currently, when I run the above code on my tab delimited file, I get something like this:

array[0] = {"First Name\tLast Name\tCode\t"=>"Luigi\tSmith\t1406\t"}

So, each array object is a hash as intended, but it has one key value pair - The entire tab delimited header row being the key, and the individual row of data being the value.

How can I alter this code to return an array of hashes with individual key value pairs, with the header of each column mapping to the row value for that column?

È stato utile?

Soluzione

It seems that the options you pass to parse are listed in ::new

>> CSV.parse("qwe\tq\twe", col_sep: "\t"){|a| p a}
["qwe", "q", "we"]

Altri suggerimenti

Use the col_sep option, this post has the code: Changing field separator/delimiter in exported CSV using Ruby CSV

also checkout the docs: http://ruby-doc.org/stdlib-2.1.0/libdoc/csv/rdoc/CSV.html

lots of good stuff in the DEFAULT_OPTIONS section

Autorizzato sotto: CC-BY-SA insieme a attribuzione
Non affiliato a StackOverflow
scroll top