How to write a tab-delimited file when the tab-delimiter comes from a database?

Christoph picture Christoph · May 2, 2011 · Viewed 10k times · Source

I have a problem really phrasing this question so i try to give an example:

The following code works and creates the expected output: a delimited file where each column is separated by a "real" tab.

CSV.open(@targetfile, "wb", "\t") { |csv| 
csv << ["row", "of", "CSV", " }

The following code does not produce the expected out.

CSV.open(@targetfile, "wb", @targetdelimiter) { |csv| 
csv << ["row", "of", "CSV", "data"] }

@targetdelimiter in this case comes from the database and is actually the string '\t' (without the quotes) which can be configured by the user.

This code produces also a delimited output, but i can see the '\t' instead of a "real" tab character.

What can I do with the second code block to get the same result as the first codeblock given that the @targetdelimiter='\t' from the db?

Answer

steenslag picture steenslag · May 2, 2011

Just gsub it and be done with it.

CSV.open(@targetfile, "wb", @targetdelimiter.gsub('\t',"\t")){ |csv| 
csv << ["row", "of", "CSV", "data"] }