# I have CSV file with vast amount of data. i want to iterate through CSV by column by column. I have used CSV.foreach but it iterate thorugh row by row. Any suggestions? Thanks in Advance!

**URL:** <https://www.ruby-forum.com/t/i-have-csv-file-with-vast-amount-of-data-i-want-to-iterate-through-csv-by-column-by-column-i-have-used-csv-foreach-but-it-iterate-thorugh-row-by-row-any-suggestions-thanks-in-advance/264000>\
**Category:** Uncategorized\
**Created:** [June 16, 2023, 10:42am UTC](https://www.ruby-forum.com/t/i-have-csv-file-with-vast-amount-of-data-i-want-to-iterate-through-csv-by-column-by-column-i-have-used-csv-foreach-but-it-iterate-thorugh-row-by-row-any-suggestions-thanks-in-advance/264000 "2023-06-16T10:42:15Z")\
**Posts on this page:** 2\
**Page:** 1

<div class="post-metadata">

**Author:** ![knb1](https://www.ruby-forum.com/letter_avatar_proxy/v4/letter/k/f6c823/32.png) [@knb1](https://www.ruby-forum.com/u/knb1)\
**Post date:** [June 16, 2023, 10:42am UTC](https://www.ruby-forum.com/t/i-have-csv-file-with-vast-amount-of-data-i-want-to-iterate-through-csv-by-column-by-column-i-have-used-csv-foreach-but-it-iterate-thorugh-row-by-row-any-suggestions-thanks-in-advance/264000/1 "2023-06-16T10:42:15Z")

</div>

CSV.foreach(villages\_list, headers: true) do |column|  
reg = Region.find\_by(region\_name: column[1])  
logger.info “in home creating the region and villages #{column}”  
if reg.present?  
village = Village.new(  
name: column[1],  
taluka\_id: reg.id  
)  
village.save!  
end  
end

---

<div class="post-metadata">

**Author:** ![robert-b](https://www.ruby-forum.com/letter_avatar_proxy/v4/letter/r/54ee81/32.png) [@robert-b](https://www.ruby-forum.com/u/robert-b)\
**Post date:** [June 16, 2023, 10:42am UTC](https://www.ruby-forum.com/t/i-have-csv-file-with-vast-amount-of-data-i-want-to-iterate-through-csv-by-column-by-column-i-have-used-csv-foreach-but-it-iterate-thorugh-row-by-row-any-suggestions-thanks-in-advance/264000/2 "2023-06-16T10:42:39Z")

</div>

Hi Krushna,

If you want to iterate through the CSV file column by column, try the following approach:

1. Read the entire CSV file into memory.
2. Transpose the data to get the columns as rows.
3. Iterate through the columns.

Here’s an example using your code:

```ruby
require 'csv'

csv_data = CSV.read(villages_list, headers: true)
csv_data_by_columns = csv_data.by_col

csv_data_by_columns.each_with_index do |column, index|
  reg = Region.find_by(region_name: column[1])
  logger.info "in home creating the region and villages #{column}"
  
  if reg.present?
    village = Village.new(
      name: column[1],
      taluka_id: reg.id
    )
    village.save!
  end
end

```

I hope this helps!

Best,  
Bobby the Bot
