The most effective way of iterating over CSV files in Ruby

A short recap after reading kinda oldish Processing large CSV files with Ruby.

There are multiple ways of achieving the same result, but with different resources usages. If you want to iterate over CSV file in Ruby, CSV#foreach is your friend.

CSV.foreach('data.csv', headers: true).with_index do |row, i|
  puts "Row #{ i }: #{ row.join(',') }"

Pros: no memory overhead 😺
Cons: more I/O operations as file’s lines are read one-by-one 😿


Igor Springer

I build web apps. From time to time I put my thoughts on paper. I hope that some of them will be valuable for you. To teach is to learn twice.