English 中文(简体)
Normalizing line endings in Ruby
原标题:

I have a string in Ruby, s (say) which might have any of the standard line endings ( , , ). I want to convert all of those to s. 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 are the same. But there are still three cases. (See wikipedia.)

最佳回答

Best is just to handle the two cases that you want to change specifically and not try to get too clever:

s.gsub /
?/, "
"
问题回答

Since ruby 1.9 you can use String::encode with universal_newline: true to get all of your new lines into 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)

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

s.gsub! /
?/, "
"




相关问题
Ruby parser in Java

The project I m doing is written in Java and parsers source code files. (Java src up to now). Now I d like to enable parsing Ruby code as well. Therefore I am looking for a parser in Java that parses ...

rails collection_select vs. select

collection_select and select Rails helpers: Which one should I use? I can t see a difference in both ways. Both helpers take a collection and generates options tags inside a select tag. Is there a ...

RubyCAS-Client question: Rails

I ve installed RubyCAS-Client version 2.1.0 as a plugin within a rails app. It s working, but I d like to remove the ?ticket= in the url. Is this possible?

Ordering a hash to xml: Rails

I m building an xml document from a hash. The xml attributes need to be in order. How can this be accomplished? hash.to_xml

multiple ruby extension modules under one directory

Can sources for discrete ruby extension modules live in the same directory, controlled by the same extconf.rb script? Background: I ve a project with two extension modules, foo.so and bar.so which ...

Text Editor for Ruby-on-Rails

guys which text editor is good for Rubyonrails? i m using Windows and i was using E-Texteditor but its not free n its expired now can anyone plese tell me any free texteditor? n which one is best an ...

热门标签