Using Ruby CSV to Retrieve a Single Column

I am trying to get one column from a csv file.

I looked at the documentation, http://www.ruby-doc.org/stdlib/libdoc/csv/rdoc/index.html but still do not understand how to use it.

If I use CSV.table , the answer is incredibly slow compared to CSV.read . I admit that the dataset that I upload is quite large, which is why I want to get only one column.

My request just looks at the moment

 @dataTable = CSV.table('path_to_csv.csv') 

and when I debug, I get an answer

  # <CSV :: Table mode: col_or_row row_count: 2104>

The documentation says that I should use by_col () , but when I try to output

 <%= debug @dataTable.by_col('col_name or index') %> 

It gives me the "undefined method" col "error"

Can someone explain to me how I should use CSV? and if there is a way to get the columns faster using "read" instead of "table"?

I use Ruby 1.92, which says it uses quickCSV, so I don't need to use the FasterCSV gem.

+4
source share
2 answers

To cut a column from csv, I would probably do something like the following:

 col_data = [] CSV.foreach(FILENAME) {|row| col_data << row[COL_INDEX]} 

This should be significantly faster than any CSV.Table operation.

+11
source

You can get values ​​from one column of csv files using the following snippet.

 @dataTable = CSV.table('path_to_csv.csv') @dataTable[:columnname] 
+4
source

All Articles