为什么 `"hello\r".chomp('')` 不删除 `"\r"`?
Why doesn't `"hello\r".chomp('')` remove `"\r"`?
尽管 Ruby reference manual 描述:
If $/
is an empty string, it will remove all trailing newlines from the string.
"hello\r".chomp('')
不会删除 "\r"
,如下所示。
"hello\r\n".chomp # => "hello"
"hello\r".chomp # => "hello"
"hello\r\n".chomp('') # => "hello"
"hello\r".chomp('') # => "hello\r"
为什么?
If $/ is an empty string, it will remove all trailing newlines from the string.
没错。 \r
又名 CR
不是换行符。这是一个回车 return 字符(不开始换行)。
至于为什么chomp('')
去掉CRLF,是因为CRLF是Windows式的换行符。 Linux 使用 LF。
旧的 Mac OSes(直到 v9)使用 CR,但最近的(OS X)不使用。因此,就 ruby 而言,"CR as a newline char" 不存在。
简单的解释就是\r
不是换行,而是回车return。所以 chomp()
完全按照手册所述进行操作。
详细解释可以在 Control_character 维基百科页面上找到。
尽管 Ruby reference manual 描述:
If
$/
is an empty string, it will remove all trailing newlines from the string.
"hello\r".chomp('')
不会删除 "\r"
,如下所示。
"hello\r\n".chomp # => "hello"
"hello\r".chomp # => "hello"
"hello\r\n".chomp('') # => "hello"
"hello\r".chomp('') # => "hello\r"
为什么?
If $/ is an empty string, it will remove all trailing newlines from the string.
没错。 \r
又名 CR
不是换行符。这是一个回车 return 字符(不开始换行)。
至于为什么chomp('')
去掉CRLF,是因为CRLF是Windows式的换行符。 Linux 使用 LF。
旧的 Mac OSes(直到 v9)使用 CR,但最近的(OS X)不使用。因此,就 ruby 而言,"CR as a newline char" 不存在。
简单的解释就是\r
不是换行,而是回车return。所以 chomp()
完全按照手册所述进行操作。
详细解释可以在 Control_character 维基百科页面上找到。