用于修改字符串外引号的 ruby 代码?
有谁知道对字符串的外部引号进行操作的 Ruby gem(或内置的或本机语法)?
我发现自己一遍又一遍地编写这样的方法:
remove_outer_quotes_if_quoted( myString, chars ) -> aString
add_outer_quotes_unless_quoted( myString, char ) -> aString
第一个测试 myString
以查看其开始和结束字符是否与 chars
中的任何一个字符匹配。如果是,则返回删除了引号的字符串。否则它会原封不动地返回。 chars
默认为引号字符列表。
第二个测试 myString
以查看它是否已以 char
开头和结尾。如果是,则返回原样的字符串。如果不是,则返回前后添加了 char
的字符串,并且任何嵌入的 char
都会用反斜杠转义。 char
默认为默认字符列表中的第一个。
(当然,我手工拼凑的方法没有如此冗长的名称。)
我在公共存储库中查找了类似的方法,但找不到类似的方法。我是唯一一个需要做很多事情的人吗?如果没有,其他人是如何做到这一点的?
Does anyone know of a Ruby gem (or built-in, or native syntax, for that matter) that operates on the outer quote marks of strings?
I find myself writing methods like this over and over again:
remove_outer_quotes_if_quoted( myString, chars ) -> aString
add_outer_quotes_unless_quoted( myString, char ) -> aString
The first tests myString
to see if its beginning and ending characters match any one character in chars
. If so, it returns the string with quotes removed. Otherwise it returns it unchanged. chars
defaults to a list of quote mark characters.
The second tests myString
to see if it already begins and ends with char
. If so, it returns the string unchanged. If not, it returns the string with char
tacked on before and after, and any embedded occurrance of char
is escaped with backslash. char
defaults to the first in a default list of characters.
(My hand-cobbled methods don't have such verbose names, of course.)
I've looked around for similar methods in the public repos but can't find anything like this. Am I the only one that needs to do this alot? If not, how does everyone else do this?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
如果你经常这样做,你可能想向 String 添加一个方法:
然后你可以调用
string.strip_quotes
。添加引号是类似的:
这称为 string.add_quotes 并在添加双引号之前使用 strip_quotes。
If you do it a lot, you may want to add a method to String:
Then you can just call
string.strip_quotes
.Adding quotes is similar:
This is called as
string.add_quotes
and uses strip_quotes before adding double quotes.这可能会解释如何删除和添加它们:
原来的两行:
剥离引号:
在需要时添加引号:
This might 'splain how to remove and add them:
The original two lines:
Stripping quotes:
Adding quotes when needed:
如果 value[0] == value[-1] && 我会使用 value = value[1...-1] %w[' "].include?(value[0])。简而言之,这个简单的代码检查字符串的第一个和最后一个字符是否相同,如果它们是单/双引号,则将其删除。另外,可以根据需要添加许多报价类型
上面的示例将打印以下内容:
I would use the
value = value[1...-1] if value[0] == value[-1] && %w[' "].include?(value[0])
. In short, this simple code checks whether first and last char of string are the same and removes them if they are single/double quote. Additionally as many as needed quote types can be added.The example above will print the following: