Ruby技术问题:无法向现有哈希追加数据,报类型转换错误
Ruby报错
no implicit conversion of String into Integer (TypeError)的原因及解决 问题场景
尝试将new_rule推送到现有安全规则集合时触发类型错误,报错信息:no implicit conversion of String into Integer (TypeError),相关代码及现有规则输出如下:
require 'json' network_sg_existing_rules = network_sg_properties["securityRules"] puts network_sg_existing_rules # 输出结果: # [{"name"=>"Port_8080", "id"=>"/subscriptions/44a91bb8-d388-467e-89e6-123456/resourceGroups/cloud-shell-storage-centralindia/providers/Microsoft.Network/networkSecurityGroups/sg_testing_temp_1/securityRules/Port_8080", "etag"=>"W/\"0d87997d-2a2a-4725-9be5-123456\"", "type"=>"Microsoft.Network/networkSecurityGroups/securityRules", "properties"=>{"provisioningState"=>"Succeeded", "protocol"=>"*", "sourcePortRange"=>"*", "destinationPortRange"=>"8080", "sourceAddressPrefix"=>"*", "destinationAddressPrefix"=>"*", "access"=>"Allow", "priority"=>100, "direction"=>"Inbound", "sourcePortRanges"=>[], "destinationPortRanges"=>[], "sourceAddressPrefixes"=>[], "destinationAddressPrefixes"=>[]}}] # Append new rule. new_rule = { :name => "rule_4", :properties => { :protocol => "TCP", :sourceAddressPrefix => "*", :destinationAddressPrefix => "*", :access => "Allow", :destinationPortRange => "22", :sourcePortRange => "*", :priority => "301", :direction => "Inbound" } } network_sg_new_rules = network_sg_existing_rules["securityRules"].push(new_rule) puts network_sg_new_rules
错误原因
数组误用哈希键访问方式
从puts network_sg_existing_rules的输出能看到,network_sg_existing_rules是一个数组(外层为方括号[]),但你用了哈希的键访问语法network_sg_existing_rules["securityRules"]来获取元素。Ruby中数组只能通过整数索引访问,传入字符串时,Ruby会尝试将其转换为整数作为索引,转换失败就触发了TypeError。冗余的键访问操作
network_sg_existing_rules本身就是network_sg_properties["securityRules"]的结果,也就是安全规则的数组集合,不需要再额外访问["securityRules"]键。
解决方法
1. 修正数组追加逻辑
直接对network_sg_existing_rules数组执行push操作,修改错误代码行:
network_sg_new_rules = network_sg_existing_rules.push(new_rule)
也可以用更简洁的数组追加运算符<<:
network_sg_existing_rules << new_rule network_sg_new_rules = network_sg_existing_rules
2. 统一数据类型(可选但推荐)
现有规则中的priority是整数类型(如100),但new_rule中的priority是字符串"301",建议统一为整数避免后续潜在问题:
new_rule = { :name => "rule_4", :properties => { # ... 其他属性保持不变 :priority => 301, # 改为整数类型 :direction => "Inbound" } }
内容的提问来源于stack exchange,提问作者user630702
相关产品推荐
相关产品推荐

