Split on different newlines

前端 未结 8 1085
自闭症患者
自闭症患者 2021-02-01 12:57

Right now I\'m doing a split on a string and assuming that the newline from the user is \\r\\n like so:

string.split(/\\r\\n/)
<         


        
8条回答
  •  孤独总比滥情好
    2021-02-01 13:13

    Another option is to use String#chomp, which also handles newlines intelligently by itself.

    You can accomplish what you are after with something like:

    lines = string.lines.map(&:chomp)
    

    Or if you are dealing with something large enough that memory use is a concern:

    .each_line do |line|
      line.chomp!
      #  do work..
    end
    

    Performance isn't always the most important thing when solving this kind of problem, but it is worth noting the chomp solution is also a bit faster than using a regex.

    On my machine (i7, ruby 2.1.9):

    Warming up --------------------------------------
               map/chomp    14.715k i/100ms
      split custom regex    12.383k i/100ms
    Calculating -------------------------------------
               map/chomp    158.590k (± 4.4%) i/s -    794.610k in   5.020908s
      split custom regex    128.722k (± 5.1%) i/s -    643.916k in   5.016150s
    

提交回复
热议问题