在 Ruby 中转义字符串 [英] escaping a string in Ruby

查看:68
本文介绍了在 Ruby 中转义字符串的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想在一些 Ruby 中插入以下作为变量的值:

I want to insert the following as the value for a variable in some Ruby:

`~!@#$%^&*()_-+={}|[]\:";'<>?,./

用双引号将它括起来是行不通的,那么有没有很好的 escape_until_the_end 类型的东西可用?

Surrounding this in double quotes doesn't work, so is there a nice escape_until_the_end sort of thing available?

推荐答案

不要使用多种方法 - 保持简单.

Don't use multiple methods - keep it simple.

转义 #、反斜杠和双引号.

Escape the #, the backslash, and the double-quote.

irb(main):001:0> foo = "`~!@\#$%^&*()_-+={}|[]\\:\";'<>?,./"
=> "`~!@\#$%^&*()_-+={}|[]\\:\";'<>?,./"

或者,如果您不想转义 #(双引号字符串中变量的替换字符),请改用并转义单引号:

Or if you don't want to escape the # (the substitution character for variables in double-quoted strings), use and escape single quotes instead:

irb(main):002:0> foo = '`~!@#$%^&*()_-+={}|[]\\:";\'<>?,./'
=> "`~!@\#$%^&*()_-+={}|[]\\:\";'<>?,./"

%q 非常适合许多其他不包含每个 ascii 标点字符的字符串.:)

%q is great for lots of other strings that don't contain every ascii punctuation character. :)

%q(text without parens)
%q{text without braces}
%Q[text without brackets with #{foo} substitution]

显然你也可以成功地在 %q() 中使用平衡括号,但我认为从维护的角度来看这有点危险,因为那里没有语义暗示你总是需要平衡你的括号在一个字符串中.

Evidently you can used balanced parens inside %q() successfully as well, but I would think that's slightly dangerous from a maintenance standpoint, as there's no semantics there to imply that you're always going to necessarily balance your parens in a string.

这篇关于在 Ruby 中转义字符串的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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