2

Is it possible to ignore or to replace with empty String, when the column is empty? My CSV looks like this:

"DE","Klasse","Deutsch", "x"
"EN","Class","Carpenter",
"DE","Klasse","Mathe",
,,,

So not all the columns are filled. There are several empty columns. It retunrs an error :

TypeError: no implicit conversion of nil into String

What I did is :

csv_contents = CSV.read("path_to_csv", options)
str=["local, type, name"]
csv_contents.each_with_index do |row, i|
if row[3]==nil
  str << row[0] + ", " + row[1] + ", " + row[2] 
end
end

end I have to modify the csv because all the rows that have "x" in the last column should be deleted. Can anyone help me? Thanks

2
  • How did you collect the csv_contents, show that part also.. Commented Feb 11, 2014 at 14:59
  • @ArupRakshit alright. I'll do it right away Commented Feb 11, 2014 at 15:00

2 Answers 2

1

You could add a method to check if the value is nil. If so, return "".

def get_row(row, i)
  row.nil? ? "" : row[i]
end

Then, use it in your code:

str << get_row(row, 0) + ", " + get_row(row, 1) + ", " + get_row(row, 2)
Sign up to request clarification or add additional context in comments.

3 Comments

@catwoman If this answer helped you, you should consider accepting it.
Yes, of course I will. I couldn't do it before, had to wait 8 min @Abdo
@Abdo Check out my one too :-)
1

Is it possible to ignore or to replace with empty String, when the column is empty?

When you have a line like foo,,bar,,that means those columns are blank. Yes you are right, but blank mean those are already empty string (""). No point here, to replace an empty string with an empty string :-). Anyway you can ignore them obviously, when you will save those data in the output file.

because all the rows that have "x" in the last column should be deleted.

That is possible, no doubt.

Here is how, I would do this :

require 'csv'

input_file_path = File.expand_path('input.csv',File.dirname(__FILE__))
output_file_path = File.expand_path('output.csv',File.dirname(__FILE__)) 

option = { :skip_blanks => true, 
           :quote_char => "\'", 
           :converters => lambda do |field|
             field.to_s.tr('"','')
           end
         }

CSV.open(output_file_path,'w',:force_quotes => true) do |out_row|
  CSV.foreach(input_file_path, option) do |in_row|
    row_to_add = in_row.reject(&:empty?)
    unless row_to_add.empty?
      row_to_add.last[/^\s*x$/i] ? out_row.puts(row_to_add[0..-2]) : out_row.puts(row_to_add)
    end
  end
end

output

"DE","Klasse","Deutsch"
"EN","Class","Carpenter"
"DE","Klasse","Mathe"

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.