删除 Ruby 中的换行符

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/17132262/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-06 06:02:17  来源:igfitidea点击:

Removing line breaks in Ruby

ruby

提问by Gediminas

I have a problem removing \nand \rtags. When I'm using double quotes, it works ok, otherwise it leaves "/". With gsub, it doesn't work without double quotes at all. Why?

我在删除\n\r标记时遇到问题。当我使用双引号时,它工作正常,否则它会离开"/". 使用 gsub,它在没有双引号的情况下根本无法工作。为什么?

<%= "Remove \n".delete('\n') %>
result: "Remove" 
<%= 'Remove \n'.delete('\n') %>
result: "Remove \" 

I found this because results it doesn't work with results from the database...

我发现这是因为结果它不适用于数据库中的结果......

回答by Sergio Tulentsev

Single-quoted strings do not process most escape sequences. So, when you have this

单引号字符串不处理大多数转义序列。所以,当你有这个

'\n'

it literally means "two character string, where first character is backslash and second character is lower-case 'n'". It does notmean "newline character". In order for \nto mean newline char, you have to put it inside of double-quoted string (which does process this escape sequence). Here are a few examples:

它的字面意思是“两个字符串,其中第一个字符是反斜杠,第二个字符是小写的 'n'”。它并不意味着“换行符”。为了\n表示换行符,您必须将它放在双引号字符串中(它确实处理此转义序列)。这里有一些例子:

"Remove \n".delete('\n') # => "Remove \n" # doesn't match
'Remove \n'.delete('\n') # => "Remove \" # see below

'Remove \n'.delete("\n") # => "Remove \n" # no newline in source string
"Remove \n".delete("\n") # => "Remove " # properly removed

NOTEthat backslash character in this particular example (second line, using single-quoted string in deletecall) is simply ignored, because of special logic in the deletemethod. See doc on String#countfor more info. To bypass this, use gsub, for example

请注意delete,由于方法中的特殊逻辑,此特定示例(第二行,在调用中使用单引号字符串)中的反斜杠字符被简单地忽略delete。有关更多信息,请参阅String#count上的文档。要绕过这一点,请使用gsub,例如

'Remove \n'.gsub('\n', '') # => "Remove "

回答by Zero Fiber

From Ruby Programming/Strings

来自Ruby 编程/字符串

Single quotes only support two escape sequences.

\' – single quote
\ – single backslash

Except for these two escape sequences, everything else between single quotes is treated literally.

单引号仅支持两个转义序列。

\' – single quote
\ – single backslash

除了这两个转义序列,单引号之间的所有其他内容都按字面处理。

So if you type \nin the irb, you get back \\n.

因此,如果您输入\nirb,您将返回\\n.

This is why you have problems with delete

这就是为什么你有问题 delete

"Remove \n".delete('\n') #=> "Remove \n".delete("\n") => "Remove \n"
'Remove \n'.delete('\n') #=> "Remove \n".delete("\n") => "Remove \"