我有file.csv
:
user,name
1,Jim
1,Jim
2,Michael
3,Scott
4,Dwight
4,Dwight
5,Pam
我只想要文件中的唯一条目之一,然后将其导入。我希望:
user,name
1,Jim
2,Michael
3,Scott
4,Dwight
5,Pam
我可以解析CSV并将其导入到数据库中。
CSV.foreach("file.csv", :headers => true).each do |row|
# do stuff to ignore dupes
# doing stuff to import to db
end
我认为我在解析过程中需要跟踪ID,但是我不确定下一步将是什么。
答案 0 :(得分:1)
可以尝试:
CSV.read("file.csv", :headers => true).uniq(&:last).each do |row|
print row
end
输出:
1,Jim
2,Michael
3,Scott
4,Dwight
5,Pam
答案 1 :(得分:0)
鉴于我的问题,我知道了。也许不是最佳实践,但这似乎可以满足我的需求。
previous_user = nil
CSV.foreach("file.csv", :headers => true).each do |row|
# do stuff to ignore dupes
current_user = row['user']
next if current_user == previous_user
# doing stuff to import to db
previous_user = current_user
end