views:

138

answers:

1

Hey. How can I get a total number of rows in a file (do not want to do it with loop). I'm reading CSV file.

Example 1

CSV.open('clients.csv', 'r')

Example 2

FasterCSV.foreach('clients.csv')

Thx.

+3  A: 

How large is your file?

This option loads the entire file into memory, so if there are size/memory concerns it might not work.

numrows = FasterCSV.read('clients.csv').size

This option uses Ruby's built-in CSV module, which as you know is quite slow, but it does work. It also loads the entire file into memory:

numrows = CSV.readlines('clients.csv').size

Both FasterCSV.read and CSV.readlines return arrays of arrays, so you can use any array magic you want on the results.

Roadmaster
Ruby 1.9 don't support FasterCSV
VP
Then I suppose the other solution might be more useful in Ruby 1.9 - it's slow but it works :) Thanks for the heads-up.
Roadmaster