On Feb 17, 2014, at 3:36 PM, Arup R. [email protected] wrote:
Ram,30
csv_file.convert do |field, info|
p row
>> [“Ram”, “30”, nil]
>> [“Sagar”, “14”, nil]
Also I found that, csv_file.convert do |field, info|..
line of codes
are not getting executed. Why so ?
As you haven’t said what you expected it to output this is a guess:
I think that you need to put the converter on the csv object you use to
read from the string, so that as each record is read it will be
processed by the converter.
For example:
#!/usr/bin/env ruby
require ‘csv’
str = <<_
name,age,eligible?
arup,27,
deep,14
Debu,26,y
Ram,30
Sagar,14
_
csv = CSV.new(str,
:headers => true,
:return_headers => true
)
csv.convert do |field, info|
if info.header == ‘eligible?’
‘Y’
else
field
end
end
CSV.open(‘test.csv’,‘w’) do |csv_file|
csv.each do |row|
csv_file << row
end
end
CSV.foreach(‘test.csv’) do |row|
p row
end
produces:
~ ∙ ruby ~/tmp/try.rb
[“name”, “age”, “eligible?”]
[“arup”, “27”, “Y”]
[“deep”, “14”, nil]
[“Debu”, “26”, “Y”]
[“Ram”, “30”, nil]
[“Sagar”, “14”, nil]
Both Debu and Arup records had a eligible? field, and when the converter
is run for it the value is replaced with a “Y”.
Hope this helps,
Mike
–
Mike S. [email protected]
http://www.stok.ca/~mike/
The “`Stok’ disclaimers” apply.