如何使用ruby [duplicate]从CSV文件中获取第二行

问题描述 投票:-3回答:1

这个问题在这里已有答案:

单击应用程序上的按钮后将下载CSV文件,并包含与表格相同的数据。场景 - :我必须测试csv文件中的数据是否包含与应用程序中包含的表相同的数据。

ruby cucumber watir-webdriver
1个回答
0
投票

您可以轻松打开CSV并获取行输入。我假设您有一个像这样的csv文件:

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

在你的应用程序或测试中做

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
© www.soinside.com 2019 - 2024. All rights reserved.