规范 Ruby 中的行结尾
我有一个 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 \n
s. 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 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
从 ruby 1.9 开始,您可以使用
String::encode
与universal_newline: true
将所有新行放入\n
同时保持编码不变:一旦处于已知的换行状态,您可以使用
:crlf_newline
自由转换回 CRLF。例如:要将未知(可能是混合)结尾的文件转换为CRLF
(例如),以二进制模式读取它,然后:Since ruby 1.9 you can use
String::encode
withuniversal_newline: true
to get all of your new lines into\n
while keeping your encoding unchanged: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 toCRLF
(for example), read it in binary mode, then :最好的方法是只处理您想要具体更改的两种情况,而不是试图变得太聪明:
Best is just to handle the two cases that you want to change specifically and not try to get too clever:
我认为最干净的解决方案是使用正则表达式:
I think the cleanest solution would be to use a regular expression:
尝试在 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.