Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

System new line separator in Ruby

Tags:

newline

ruby

How can I determine new line separator used by OS (LF, CR/LF or other), in Ruby?

like image 560
Lavir the Whiolet Avatar asked Nov 03 '11 13:11

Lavir the Whiolet


People also ask

How do you make a new line character in Ruby?

\n is the newline character. It prints a new line.

How do you add a line break in Ruby?

\r\n should probably do the trick.

What is carriage return in Ruby?

chomp is a String class method in Ruby which is used to returns new String with the given record separator removed from the end of str (if present). chomp method will also remove carriage return characters (that is it will remove \n, \r, and \r\n) if $/ has not been changed from the default Ruby record separator, t.


1 Answers

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.

like image 172
Zabba Avatar answered Oct 20 '22 09:10

Zabba