System New Line Separator in Ruby

System new line separator in Ruby

Not sure if there is a direct solution to get the type of newline based on OS, but there is the $/ variable that holds the "input record separator". By default this will be "\n". (Documentation here)

You can detect the OS and then set $/ to the "correct" value.

To detect OS:

puts RUBY_PLATFORM                  # => 'i386-linux'
require 'rbconfig'
puts Config::CONFIG['target_cpu'] # => 'i386'
puts Config::CONFIG['target_os'] # => 'linux'
puts Config::CONFIG['host_cpu'] # => 'i686'
puts Config::CONFIG['host_os'] # => 'linux-gnu'

Also remember that when reading files, they could have a mix of various line separators - for example if a text file was edited in both Windows and Linux. Thus if you're processing files, do not depend on the "OS line seperator" exclusively.

Universal newline support in Ruby that includes \r (CR) line endings

You could use :row_sep => :auto:

:row_sep
The String appended to the end of each row. This can be set to the special :auto setting, which requests that CSV automatically discover this from the data. Auto-discovery reads ahead in the data looking for the next "\r\n", "\n", or "\r" sequence.

There are some caveats of course, see the manual linked to above for details.

You could also manually clean up the EOLs with a bit of gsubing before handing the data to CSV for parsing. I'd probably take this route and manually convert all \r\ns and \rs to single \ns before attempting to parse the CSV. OTOH, this won't work that well if there is embedded binary data in your CSV where \rs mean something. On the gripping hand, this is CSV we're dealing with so who knows what sort of crazy broken nonsense you'll end up dealing with.

Split on different newlines

Did you try /\r?\n/ ? The ? makes the \r optional.

Example usage: http://rubular.com/r/1ZuihD0YfF

How do i create line breaks in ruby?

Use puts since it will automatically add a newline for you:

puts "Hi"
puts "Hi"

If you want to make an explicit newline character then you'll need to know what kind of system(s) on which your program will run:

print "Hi\n"   # For UNIX-like systems including Mac OS X.
print "Hi\r\n" # For Windows.

How can I remove a newline character from the line above in Ruby?

I would use gsub:

string = "GTSS/230028GG/JUL15/LL:123456X3-0051234G4/DES/000G/57NM/57NM/095T\n/002GTS////gts"
string.gsub("\n/", '/')
#=> "GTSS/230028GG/JUL15/LL:123456X3-0051234G4/DES/000G/57NM/57NM/095T/002GTS////gts"

Does Ruby have a constant for cross-platform EOL somewhere?

Ruby's got four (!)

p $/
p $-0
require 'English'
p $RS
p $INPUT_RECORD_SEPARATOR

Using IO#puts (= File#puts) will take care of the proper EOL, no need to set it manually.

Normalizing line endings in Ruby

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"


Related Topics



Leave a reply



Submit