如何删除字符串“\n"?从 Ruby 字符串中? [英] How can I remove the string "\n" from within a Ruby string?

查看:81
本文介绍了如何删除字符串“\n"?从 Ruby 字符串中?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有这个字符串:

"some text\nandsomemore"

我需要从中删除\n".我试过了

I need to remove the "\n" from it. I've tried

"some text\nandsomemore".gsub('\n','')

但它不起作用.我该怎么做?感谢阅读.

but it doesn't work. How do I do it? Thanks for reading.

推荐答案

您需要在 gsub 中使用 "\n" 而不是 '\n'.不同的引号表现不同.

You need to use "\n" not '\n' in your gsub. The different quote marks behave differently.

双引号 " 允许字符扩展和表达式插值,即它们允许您使用像 \n 这样的转义控制字符来表示它们的真实值,在这种情况下,newline,并允许使用 #{expression} 以便您可以将变量以及几乎任何您喜欢的 ruby​​ 表达式编织到文本中.

Double quotes " allow character expansion and expression interpolation ie. they let you use escaped control chars like \n to represent their true value, in this case, newline, and allow the use of #{expression} so you can weave variables and, well, pretty much any ruby expression you like into the text.

另一方面,单引号 ' 按字面意思处理字符串,因此没有扩展、替换、插值等.

While on the other hand, single quotes ' treat the string literally, so there's no expansion, replacement, interpolation or what have you.

在这种特殊情况下,最好使用 .delete.tr String 方法删除换行符.

In this particular case, it's better to use either the .delete or .tr String method to delete the newlines.

查看此处了解更多信息

这篇关于如何删除字符串“\n"?从 Ruby 字符串中?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆