用于修改字符串外引号的 ruby​​ 代码? [英] ruby code for modifying outer quotes on strings?

查看:40
本文介绍了用于修改字符串外引号的 ruby​​ 代码?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

有谁知道对字符串的外引号进行操作的 Ruby gem(或内置或本地语法)?

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

第一个测试 myString 以查看它的开始和结束字符是否与 chars 中的任何一个字符匹配.如果是,则返回去掉引号的字符串.否则它返回它不变.chars 默认为引号字符列表.

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.

第二个测试 myString 以查看它是否已经以 char 开头和结尾.如果是,则返回未更改的字符串.如果不是,则返回前后附加了 char 的字符串,并且任何嵌入的 char 都用反斜杠转义.char 默认为默认字符列表中的第一个.

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?

推荐答案

如果你经常这样做,你可能想给 String 添加一个方法:

If you do it a lot, you may want to add a method to String:

class String
  def strip_quotes
    gsub(/\A['"]+|['"]+\Z/, "")
  end
end

然后你可以调用string.strip_quotes.

添加引号类似:

class String
  def add_quotes
     %Q/"#{strip_quotes}"/ 
  end
end

这被称为 string.add_quotes 并在添加双引号之前使用 strip_quotes.

This is called as string.add_quotes and uses strip_quotes before adding double quotes.

这篇关于用于修改字符串外引号的 ruby​​ 代码?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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