[英]OpsWorks Ruby returning nil for valid regex test
在OpsWorks中,我正在尝试在给定节点的主机名上测试数字后缀,并在不为1的情况下提取该数字。如果该数字不为1,则我使用此正则表达式来匹配该数字:
/([\d]+)$/
这是针对遵循此模式的节点命名方案运行的:
我已经使用Rubular验证了此作品: http: //rubular.com/r/Ei0kqjaxQn
但是,当我使用OpsWorks对实例运行此命令时,无论主机名末尾有多少,此匹配都将返回nil。 OpsWorks代理版本是在撰写本文档时最新的版本(4023),使用的是Chef 12.13.37。
这是食谱中尝试使用匹配数字的代码:
short_app_name.to_s + node['hostname'][/([\d]+)$/, 1].to_s + '.' + app['domains'].first
运行失败,类型错误, no implicit conversion of nil into String
。 但是,在检查节点的数字后缀时,针对该属性的正则表达式搜索会在配方的早期进行。 我应该使用其他方法来提取节点的后缀吗?
编辑: app['domains'].first
已填充。 如果将它替换为domain.com
,则该行仍会失败,并出现相同的类型错误。
从食谱代码和错误消息来看,问题可能在于app['domains']
在运行期间为空数组。 因此,您可能需要验证其值是否正确。
当我复制您的正则表达式并将其粘贴到我的终端以进行测试时,正则表达式末尾的美元符号后面有一个软连字符,删除该字符可使事情正常进行:
即使从终端复制网站,该网站也没有显示,但屏幕截图显示了该问题:
第二行('irb(main):002:0')是我从您的食谱代码复制/粘贴的内容,字符为“ \\ xc2 \\ xad”
您的错误与正则表达式无关。 问题是当您尝试将现有String
与
app['domains'].first
这是唯一会发生此错误的地方,因为即使您的String#slice
返回nil
您to_s
调用to_s
所以它是一个空String
但是String
+ nil
,如果app['domains'].first
为nil
会是这种情况引发此错误。
分解
#short_app_name can be nil because of explicit #to_s
short_app_name.to_s
####
# assuming node is a Hash
# node must have 'hostname' key
# or NoMethodError: undefined method `[]' for nil:NilClass wil be raised
# node['hostname'][/([\d]+)$/, 1] can be nil because of explicit #to_s
node['hostname'][/([\d]+)$/, 1].to_s
#####
# assuming app is a Hash
# app must contain 'domains' key and the value must respond to first
# and the first value must be a String or be implicitly coercible (#to_str) or it will fail with
# TypeError: no implicit conversion of ClassName into String
# could explicitly coerce (#to_s) like you do previously
app['domains'].first
例:
node = {"hostname" => 'nodable'}
app = {"domains" => []}
node['hostname'][/([\d]+)$/, 1]
#=> nil
node['hostname'][/([\d]+)$/, 1].to_s
#=> ""
app["domains"].first
#=> nil
node['hostname'][/([\d]+)$/, 1].to_s + '.' + app["domains"].first
#=> TypeError: no implicit conversion of nil into String
node = {"hostname" => 'node2'}
app = {"domains" => ['here.com']}
node['hostname'][/([\d]+)$/, 1].to_s + '.' + app["domains"].first
#=> "2.here.com"
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.