我有两个 CSV 文件:“用户”和“注册”:
001.csv:
user_id,user_name,state
12345,test_account,active
002.csv:
course_id,user_id,state
67890,12345,active
我需要创建一个像 active_enrollments.csv 这样的文件:
course_id,user_name
67890,test_account
在不多次循环文件的情况下,如何解析这些文件以生成文件 active_enrollments.csv?
这是我到目前为止所拥有的,但我得到了很多重复:
require 'csv'
CSV.open("active-enrollments.csv", "wb") do |csv|
csv << ["course_id", "user_name", "user_id","course_name", "status"]
end
Dir["csvs/*.csv"].each do |file|
#puts file
CSV.foreach(file, :headers => true) do |row|
if row['user_id'] && row ['course_id'] #finds enrollment csvs
if row['state'] == "active" #checks for active enrollments
state = row['state']
course_id = row['course_id']
user_id = row['user_id']
Dir["csvs/*.csv"].each do |files|
CSV.foreach(files, :headers => true) do |user|
if user['user_name']
if user_id == user['user_id']
user_name = user['user_name']
Dir["csvs/*.csv"].each do |file|
CSV.foreach(file, :headers => true) do |courses|
if course_id == courses['course_id']
course_name = courses['course_name']
CSV.open("active-enrollments.csv", "a") do |csv|
csv << [course_id, user_name, user_id, course_name, state]
end
end
end
end
end
end
end
end
end
end
end
end
我知道这很简单,但如果不多次循环文件并生成大量重复项,我似乎无法获得它。