tags:

views:

85

answers:

3

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

A: 

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.

Ash
thanks, but this isn't a one-off; this is for processing data in Ruby, not processing Ruby files.
Peter
A: 

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

s.gsub! /\r\n?/, "\n"
Mikael S
oops, this has a trap: double line breaks like `\n\n` will become `\n`.
Peter
Oops, thanks for pointing that out, seems jleedev was a bit faster though.
Mikael S
+4  A: 

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"
jleedev
Two things: You have to put \r\n first in the regex or else it will never match (because anyhing that could otherwise matched b \r\n will be matched by \r first). And '\n' == "\\n", while what you want is "\n".
sepp2k
Change the single quotes to double quotes. Otherwise it doesn't work as intended.
Mikael S
It seems we're all on the same page :)
jleedev
nicely done that you don't bother changing the default case (`\n` -> `\n` is unnecessary. didn't quite realise this at first :)
Peter