From: Antony Nambikkai on
Hi Friends,

I am having a role.csv file as like

emp_id,dep_id,role,salary,accepted
1,1,SSE,10000,YES
2,2,SSE,11000,NO
3,1,SSE,9000,YES
4,2,SSE,12000,YES
5,1,SSE,8000,NO

Now, I need to update this role.csv file as like below

emp_id,dep_id,role,salary,accepted
1,1,SSE,10000,NO
2,2,SSE,11000,YES
3,1,SSE,9000,NO
4,2,SSE,12000,YES
5,1,SSE,8000,NO

I tried with FasterCSV and CSV class none of them provide a full access
mode to edit this CSV file.

I have a sample code but thats not looking very effective (but working
fine)

Note : CSV file is a sample one (Don't think Logic in that)

def update_csv_report( emp_id, dep_id, is_accepted )
new_rows = Array.new
CSV.open('role.csv', 'r') do |row|
if (row[0] == emp_id && row[1] == dep_id)
new_rows << [row[0], row[1], row[2], row[3], is_accepted]
else
new_rows << [row[0], row[1], row[2], row[3], row[4]]
end
end

CSV.open('role.csv', 'w') do |writer|
new_rows.each do |row|
writer << row
end
end
end

I am facing 2 issues in this

1. For every updating the CSV file, I am rewriting the whole CSV file.
That not a teddy way to do it.
2. I am opening the file first time for reading and 2nd time for
writing. That is also not convincing me.

Please help me in this. How to Improve this code. Main motive is to
updated a particular field instead of rewriting the whole CSV file.

Cheers,
Antony Prabhu N.
--
Posted via http://www.ruby-forum.com/.