Ruby on Rails中如何将字符串内的单引号替换为双引号
解决方案
方法1:使用gsub完成替换
你之前调用gsub未生效大概率是引号转义处理错误,以下是可直接运行的实现代码:
current_res = 25 lowest_res = 15 str = "The result of the child is '#{current_res}' and the lowest grade is '#{lowest_res }'." # 核心替换逻辑:全局替换所有单引号为双引号 processed_str = str.gsub("'", '"') # 输出验证 puts processed_str # 输出结果:The result of the child is "25" and the lowest grade is "15".
你也可以用正则形式实现相同效果:
processed_str = str.gsub(/'/, '"')
方法2:构造字符串时直接插入双引号
如果是从头生成该字符串,你也可以在定义阶段就转义内部双引号,避免后续替换操作:
current_res = 25 lowest_res = 15 # 用反斜杠转义字符串内部的双引号 str = "The result of the child is \"#{current_res}\" and the lowest grade is \"#{lowest_res}\"."
第一种方案适合已生成字符串的批量替换场景,第二种方案适合新建字符串的场景。
内容的提问来源于stack exchange,提问作者moh19814
相关产品推荐
相关产品推荐

