我写了这样的代码:
require 'csv'
people = CSV.parse(File.read("import1.csv"))
puts people[0][0]
puts people[0][1]
puts people[0][2]
我现在如何阅读人们的所有元素?
答案 0 :(得分:1)
我不能100%确定你想要实现的目标。你能扩展你想要做的事情吗?您是否考虑过轮流解析文件中的每一行,从而分别对每个人进行操作? e.g。
CSV.foreach("path/to/file.csv") do |person|
first_name = person[0]
last_name = person[1]
# ... do something with the person - add to an array, construct a Person object etc
end
并且,如果您有标题,只需添加:headers => true
选项,如下所示:
CSV.foreach("path/to/file.csv", :headers => true) do |person|
first_name = person[0]
last_name = person[1]
# ... do something with the person - add to an array, construct a Person object etc
end