Normalizing line endings in Ruby

2019-02-02 21:02发布

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

4条回答
神经病院院长
2楼-- · 2019-02-02 21:37

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"
查看更多
等我变得足够好
3楼-- · 2019-02-02 21:43

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.

查看更多
等我变得足够好
4楼-- · 2019-02-02 21:52

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

s.gsub! /\r\n?/, "\n"
查看更多
Explosion°爆炸
5楼-- · 2019-02-02 21:57

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)
查看更多
登录 后发表回答