Ruby 中的系统换行符 [英] System new line separator in Ruby
问题描述
如何确定 Ruby 中操作系统(LF、CR/LF 或其他)使用的换行符?
How can I determine new line separator used by OS (LF, CR/LF or other), in Ruby?
推荐答案
不确定是否有直接的解决方案来获取基于 OS 的换行符类型,但是有 $/
变量保存输入记录分隔符".默认情况下,这将是\n".(此处的文档)
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.
检测操作系统:
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'
还请记住,在读取文件时,它们可能会混合使用各种行分隔符 - 例如,如果在 Windows 和 Linux 中编辑了文本文件.因此,如果您正在处理文件,请不要只依赖操作系统行分隔符".
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.
这篇关于Ruby 中的系统换行符的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!