How to fetch second row from the CSV file using ruby

491 views Asked by At

The CSV file will be downloaded after clicking on the button present on the application and contains the same data as the table. Scenario-: I have to test the whether the data in the csv file contains the same data as the table contains on the application.

1

There are 1 answers

3
Simon Franzen On

You can easily open the CSV and fetch the rows input. I assume you have a csv file like this:

id,attr1,attr2,attr3
1,dat1,dat1,dat1
2,dat2,dat2,dat2

In your application or test do

require 'csv'

csv_file_name = 'path_to_file.csv'

csv_file = File.open(csv_file_name, 'r')
csv = CSV.parse(csv_file, :headers => true)

csv.each do |row|
  row = row.to_hash.with_indifferent_access
  row_hash = row.to_hash.symbolize_keys

  // access to data in the row
  puts row_hash[:id]
  puts row_hash[:attr1]
  puts row_hash[:attr2]
  puts row_hash[:attr3]
end