在红宝石中逃避双引号

时间:2013-11-08 12:22:24

标签: ruby-on-rails ruby regex

如何在字符串中将double-quotes替换为&quote;? 这就是我的尝试:

1.9.3-p362 :009 > a =  "\"That's it\", she said." 
 => "\"That's it\", she said." 
1.9.3-p362 :010 > a.tr('"', "&quote;")
 => "&That's it&, she said." 

正如您所看到的那样,&quotes;而不是&,我有任何想法?

1 个答案:

答案 0 :(得分:4)

使用gsub代替

a.gsub(/\"/, "&quote;")

# without regex as noted by hirolau
a.gsub("\"", "&quote;")

# => "&quote;That's it&quote;, she said."