Normalizing line endings in Ruby

后端 未结 4 884
爱一瞬间的悲伤
爱一瞬间的悲伤 2020-12-29 04:01

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

相关标签:
4条回答
  • 2020-12-29 04:15

    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"
    
    0 讨论(0)
  • 2020-12-29 04:24

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

    s.gsub! /\r\n?/, "\n"
    
    0 讨论(0)
  • 2020-12-29 04:32

    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.

    0 讨论(0)
  • 2020-12-29 04:34

    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)
    
    0 讨论(0)
提交回复
热议问题