문제

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?

도움이 되었습니까?

해결책

Just gsub it and be done with it.

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

다른 팁

\t is replaced by an actual tab character (ASCII 0x09, or Char(9)) when it's used as a delimiter in your first example. In the second, it's not being replaced, and it's being used as the literal character sequence \ and t. You might have luck if you don't have the users store the escape sequence, and instead use something like TAB or NEWLINE, which you can then read from the database and convert to the proper character instead (or you can just convert them from the literals to the proper character).

라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top