System new line separator in Ruby

前端 未结 3 2029
青春惊慌失措
青春惊慌失措 2021-01-18 10:53

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

相关标签:
3条回答
  • 2021-01-18 11:28

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

    0 讨论(0)
  • 2021-01-18 11:44
    File.open("some_temporary_file", "w") { |file| file.puts }
    new_line_separator =
      File.open("some_temporary_file", "rb") { |file| file.read }
    
    0 讨论(0)
  • 2021-01-18 11:45

    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.

    0 讨论(0)
提交回复
热议问题