如何检查字符串对象中的双引号

时间:2015-07-30 21:30:55

标签: ruby string

我正在尝试创建一个名为contains_double_quotes(argument)?的方法,该方法检查字符串argument是否包含引号。换句话说,它应该返回

    如果trueargument,则
  • "\"which one is your favorite\""
  • 如果falseargument"hello",则
  • "this is a regular string value"

我尝试了如下,但我不确定这是否是最好的方法。这种逻辑会出现什么问题?

def contains_double_quotes(argument)
  argument.include?("\"")
end

我从此调用中获得true后,我想从argument中删除双引号,以便将其用作普通字符串值。如何从中删除双引号?

3 个答案:

答案 0 :(得分:2)

用空字符串替换所有双引号:

string.tr "\"", ""

答案 1 :(得分:2)

基准可能很有用:

require 'fruity'

str = '"' + ('a'..'z').to_a.join * 10 + '"'
compare {
  _delete { str.delete('"') }
  _gsub   { str.gsub('"', '') }
  _tr     { str.tr('"', '') }
}

# >> Running each test 2048 times. Test will take about 1 second.
# >> _gsub is faster than _delete by 10.000000000000009% ± 10.0%
# >> _delete is faster than _tr by 10.000000000000009% ± 10.0%
  

你可以添加删除!

以下是各个!版本的比较:

require 'fruity'

str = '"' + ('a'..'z').to_a.join * 10 + '"'
compare {
  _delete! { str.dup.delete!('"') }
  _gsub!   { str.dup.gsub!('"', '') }
  _tr!     { str.dup.tr!('"', '') }
}

# >> Running each test 2048 times. Test will take about 1 second.
# >> _delete! is faster than _tr! by 10.000000000000009% ± 10.0%
# >> _tr! is faster than _gsub! by 19.999999999999996% ± 10.0%

该字符串必须为dup,否则针对它的第一个操作将更改原始字符串,从而使结果倾斜。

答案 2 :(得分:0)

如果您通过检测报价而尝试实现的目标是在之后将其删除,则只需将其删除即可。

"\"which one is your favorite\"".gsub /"/, ''