规范 Ruby 中的行结尾

发布于 2024-08-12 19:21:13 字数 414 浏览 5 评论 0原文

我有一个 Ruby 字符串,s(比如说),它可能有任何标准行结尾(\n\r\n、 <代码>\r)。我想将所有这些转换为 \n 。最好的办法是什么?

这似乎是一个非常常见的问题,但没有太多关于它的文档。显然有简单粗暴的解决方案,但是有没有内置的东西可以处理这个问题?

优雅、惯用的 Ruby 解决方案是最好的。

编辑:意识到 ^M\r 是相同的。但仍然存在三种情况。 (参见维基百科。)

I have a string in Ruby, s (say) which might have any of the standard line endings (\n, \r\n, \r). I want to convert all of those to \ns. What's the best way?

This seems like a super-common problem, but there's not much documentation about it. Obviously there are easy crude solutions, but is there anything built in to handle this?

Elegant, idiomatic-Ruby solutions are best.

EDIT: realized that ^M and \r are the same. But there are still three cases. (See wikipedia.)

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

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

发布评论

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

评论(4

一口甜 2024-08-19 19:21:13

从 ruby​​ 1.9 开始,您可以使用 String::encodeuniversal_newline: true 将所有新行放入 \n 同时保持编码不变:

s.encode(s.encoding, universal_newline: true)

一旦处于已知的换行状态,您可以使用 :crlf_newline 自由转换回 CRLF。例如:要将未知(可能是混合)结尾的文件转换为 CRLF (例如),以二进制模式读取它,然后:

s.encode(s.encoding, universal_newline: true).encode(s.encoding, crlf_newline: true)

Since ruby 1.9 you can use String::encode with universal_newline: true to get all of your new lines into \n while keeping your encoding unchanged:

s.encode(s.encoding, universal_newline: true)

Once in a known newline state you can freely convert back to CRLF using :crlf_newline. eg: to convert a file of unknown (possibly mixed) ending to CRLF (for example), read it in binary mode, then :

s.encode(s.encoding, universal_newline: true).encode(s.encoding, crlf_newline: true)
围归者 2024-08-19 19:21:13

最好的方法是只处理您想要具体更改的两种情况,而不是试图变得太聪明:

s.gsub /\r\n?/, "\n"

Best is just to handle the two cases that you want to change specifically and not try to get too clever:

s.gsub /\r\n?/, "\n"
回忆躺在深渊里 2024-08-19 19:21:13

我认为最干净的解决方案是使用正则表达式:

s.gsub! /\r\n?/, "\n"

I think the cleanest solution would be to use a regular expression:

s.gsub! /\r\n?/, "\n"
迟到的我 2024-08-19 19:21:13

尝试在 NetBeans IDE 上打开它们 - 它之前在我从其他地方打开的一个项目中询问过我是否想要修复行结尾。我认为可能也有一个菜单选项可以做到这一点,但这将是我要尝试的第一件事。

Try opening them on NetBeans IDE - Its asked me before, on one of the projects I've opened from elsewhere, if I wanted to fix the line endings. I think there might be a menu option to do it too, but that would be the first thing I would try.

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