Hi, i use the following code to obtain data from my csv file and
transfer it into a class:
ef = EfficiencyE.new
pp ef.blank = fields[1].tr_s(’"’, ‘’).strip
i put pp to see the output and the output says:
“”
“Efficiency (Energy)”
“”
“Turn-off unnecessary lights/equipment”
C:/Users/Hekmatyer/Documents/NetBeansProjects/Nizam_BARU/lib/final.rb:574:in
block in <main>': undefined method
tr_s’ for nil:NilClass
(NoMethodError)
from
C:/Users/Hekmatyer/Documents/NetBeansProjects/Nizam_BARU/lib/final.rb:559:in
each_line' from C:/Users/Hekmatyer/Documents/NetBeansProjects/Nizam_BARU/lib/final.rb:559:in
’
I think i know the problem because there are empty content in my csv
file. So how do i deal with this empty (nil) content?
Nizam
On 02/04/2011 08:34 PM, Kamarulnizam R. wrote:
“”
I think i know the problem because there are empty content in my csv
file. So how do i deal with this empty (nil) content?
Ideally, you would be able to fix your CSV data to avoid the issue. 
Assuming that’s not an option, you could do something like the
following:
pp ef.blank = fields[1].to_s.tr_s(’"’, ‘’).strip
For the fields that are not nil, to_s will be called, but since they
should be strings already, that’s effectively a no-op. For nil values,
the to_s method will return an empty string.
If you need to use something other than an empty string as a replacement
for nil values (such as using “Error!” instead), you could do this:
pp ef.blank = (fields[1] || “Error!”).tr_s(’"’, ‘’).strip
The string “Error!” will be used in place of any nil field while non-nil
fields will be used directly.
-Jeremy