I’m getting from csv file some data (also how to select first 20 in csv?), for example:
A B C
D E F
also method:
def common_uploader
require 'csv'
arr = CSV.read("/#{Rails.public_path}/uploads_prices/"+params[:file], {:encoding => "CP1251:UTF-8", :col_sep => ";", :row_sep => :auto, :headers => :none})
@csv = []
@csv << arr
end
so it is array of arrays…
But how can i view it normaly in haml view?
How can i view array of arrays?
i tried something like (also in each file i have different count of columns):
view:
= @csv.first.each do |a|
= a[:1]
Help me please to view csv data.
There are several ways you can read a set number of records, and you need to pick which to use based on the anticipated size of your data source.
Starting with a CSV file:
The simplest ways to read a fixed number of records would be one of these:
Which returns an array of two sub-arrays:
An alternate is:
Which returns the same result, an array of two sub-arrays:
Both of these are fine for small input files, but will have problems if you are reading a few lines from a big input file. They will force Ruby to read the entire file into memory and create an intermediate array before slicing off the number of records you want. Where I work it’s nothing for us to get gigabyte file sizes, so grabbing a small section of those files would make Ruby and the system do an inordinate amount of work building the intermediate array then throwing it away.
You are better off to only read the minimum number of records needed. Sometimes lines need to be skipped before reading; This demonstrates that idea, along with handling
EOFErrorif the input file’s EOF is encountered unexpectedly:Replace
5with the number of records to skip, and2with the number to read. For that example I deliberately read off the end of the file to show how to skip lines, read some and then handle the EOF situation cleanly.The data looks like:
Because I’m using
File.openwith a block, the file is closed automatically after the block exists, avoiding leaving an open filehandle hanging around.The HAML output section of your question isn’t well defined at all, but this is one way to output the data:
Which results in this output of a simple HTML table:
EDIT:
Using this as my test data:
and this code:
I get this output:
I made a minor change to move
arrayoutside theFile.openblock, nothing else is different.