How can I determine new line separator used by OS (LF, CR/LF or other), in Ruby?
\n is the newline character. It prints a new line.
\r\n should probably do the trick.
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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With