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!

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

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:

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

1 Like