Search code examples
rubynewlineline-breaks

Normalizing line endings in Ruby


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


Solution

  • 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"