System new line separator in Ruby

余生颓废 提交于 2021-01-20 04:23:40

问题


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


回答1:


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.




回答2:


File.open("some_temporary_file", "w") { |file| file.puts }
new_line_separator =
  File.open("some_temporary_file", "rb") { |file| file.read }



回答3:


You shouldn't need to. In your case, I think you can just use FileUtils.



来源:https://stackoverflow.com/questions/7995581/system-new-line-separator-in-ruby

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!