问题描述
我想在 Ruby 中从字符串中去除前导和尾随引号.引号字符将出现 0 次或 1 次.例如,以下所有内容都应转换为 foo,bar:
I want to strip leading and trailing quotes, in Ruby, from a string. The quote character will occur 0 or 1 time. For example, all of the following should be converted to foo,bar:
"foo,bar"
"foo,bar
foo,bar"
foo,bar
推荐答案
你也可以使用 chomp
函数,但不幸的是它只能在字符串的末尾工作,假设有一个反向 chomp,你可以:
You could also use the chomp
function, but it unfortunately only works in the end of the string, assuming there was a reverse chomp, you could:
'"foo,bar"'.rchomp('"').chomp('"')
实现 rchomp
很简单:
class String
def rchomp(sep = $/)
self.start_with?(sep) ? self[sep.size..-1] : self
end
end
请注意,您也可以使用效率稍低的版本进行内联:
Note that you could also do it inline, with the slightly less efficient version:
'"foo,bar"'.chomp('"').reverse.chomp('"').reverse
从 Ruby 2.5 开始,rchomp(x)
以 delete_prefix
和 chomp(x)
可用作 delete_suffix
,这意味着您可以使用
Since Ruby 2.5, rchomp(x)
is available under the name delete_prefix
, and chomp(x)
is available as delete_suffix
, meaning that you can use
'"foo,bar"'.delete_prefix('"').delete_suffix('"')
这篇关于如何在 Ruby 中从字符串中去除前导和尾随引号的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!