ruby - 在(双引号)heredoc 中使用 `gsub` 不起作用
问题描述
似乎gsub
在(双引号)heredoc 内部使用不会评估 的结果gsub
,如下所示:
class Test
def self.define_phone
class_eval <<-EOS
def _phone=(val)
puts val
puts val.gsub(/\D/,'')
end
EOS
end
end
Test.define_phone
test = Test.new
test._phone = '123-456-7890'
# >> 123-456-7890
# >> 123-456-7890
第二个puts
应该打印1234567890
,就像在这种情况下一样:
'123-456-7890'.gsub(/\D/,'')
# => "1234567890"
heredoc 内部发生了什么?
解决方案
问题出\D
在正则表达式中。当 heredoc 被评估为字符串时,它将被评估,这会导致D
:
"\D" # => "D"
eval("/\D/") #=> /D/
另一方面,\D
在单引号内不会被评估为D
:
'\D' # => "\\D"
eval('/\D/') # => /\D/
因此,将 heredoc 终止符EOS
用单引号括起来以实现您想要的:
class Test
def self.define_phone
class_eval <<-'EOS'
def _phone=(val)
puts val
puts val.gsub(/\D/,'')
end
EOS
end
end
Test.define_phone
test = Test.new
test._phone = '123-456-7890'
# >> 123-456-7890
# >> 1234567890
如果您在没有包装的情况下运行上述代码EOS
,gsub
将尝试替换val
. 看到这个:
test._phone = '123-D456-D7890DD'
# >> 123-D456-D7890DD
# >> 123-456-7890
推荐阅读
- java - 检查对请求的响应是否成功的最简单方法是什么?
- xcode - 无法在 Xcode 13.1 中查看 StoryBoard 或项目目标
- android - Web 代理发布方法中的 Dotmim.Sync 空引用异常
- python - 无法在 Pycharm 上使用 Selenium 打开网站
- regex - 如何获得释放值?
- javascript - Moment js添加日期和格式失败
- javascript - Visual Studio Code - 格式化代码样式
- json - 如何从 SP API 获取亚马逊履行中心 ID
- python - 如何更改代码以使其不出现 html 标签
- jquery - 在 C# UI 中捕获 SSRS/PowerBI/Tableau 报告错误