在Ruby中规范行尾 [英] Normalizing line endings in Ruby
问题描述
我在Ruby中有一个字符串,s
(例如),该字符串可能具有任何标准行结尾(\n
,\r\n
,\r
).我想将所有这些都转换为\n
.最好的方法是什么?
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?
优雅,惯用的Ruby解决方案是最好的.
意识到^M
和\r
是相同的.但是仍然有三种情况. (请参见维基百科.)
realized that ^M
and \r
are the same. But there are still three cases. (See wikipedia.)
推荐答案
最好只是处理您要专门更改的两种情况,而不要变得太聪明:
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"
这篇关于在Ruby中规范行尾的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!