当制表符分隔符来自数据库时,如何编写制表符分隔文件?

发布于 2024-11-04 10:35:48 字数 566 浏览 0 评论 0原文

我在表达这个问题时遇到了问题,所以我尝试举一个例子:

以下代码可以工作并创建预期的输出:一个分隔文件,其中每列由“真实”选项卡分隔。

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

以下代码不会产生预期的输出。

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

在本例中,@targetdelimiter 来自数据库,实际上是字符串 '\t'(不带引号),可由用户配置。

此代码还生成分隔输出,但我可以看到 '\t' 而不是“真正的”制表符。

考虑到来自数据库的 @targetdelimiter='\t' ,我可以对第二个代码块做什么以获得与第一个代码块相同的结果?

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?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

趴在窗边数星星i 2024-11-11 10:35:48

只需 gsub 即可完成。

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

Just gsub it and be done with it.

CSV.open(@targetfile, "wb", @targetdelimiter.gsub('\t',"\t")){ |csv| 
csv << ["row", "of", "CSV", "data"] }
一场春暖 2024-11-11 10:35:48

在第一个示例中用作分隔符时,\t 会被替换为实际的制表符(ASCII 0x09Char(9)) 。在第二个中,它没有被替换,而是被用作文字字符序列 \t。如果您没有让用户存储转义序列,而是使用诸如 TABNEWLINE 之类的内容,那么您可能会很幸运,然后您可以从数据库中读取并转换它们改为正确的字符(或者您可以将它们从文字转换为正确的字符)。

\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).

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文