How can I determine new line separator used by OS (LF, CR/LF or other), in Ruby?
You shouldn't need to. In your case, I think you can just use FileUtils.
File.open("some_temporary_file", "w") { |file| file.puts }
new_line_separator =
File.open("some_temporary_file", "rb") { |file| file.read }
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.