Ruby向JSON的securityRules数组追加数据报NoMethodError解决方法
报错原因
NoMethodError: undefined method 'push'是调用方法的对象类型不匹配导致的:
test = network_sg.properties返回的是资源属性的Hash(哈希)对象,push是Array(数组)的内置方法,哈希对象没有该方法,直接调用必然报错- 你要追加内容的目标不是整个properties哈希,是哈希内
securityRules字段对应的数组。
正确实现代码
先做边界兼容:如果securityRules字段不存在、值为nil或者空数组,先统一初始化为数组类型,再执行追加操作,完全覆盖空数组场景的追加需求:
NETWORK_SG = Azure::Armrest::Network::NetworkSecurityGroupService.new(conf) network_sg = NETWORK_SG.get('testing_123', rg) props = network_sg.properties # 兼容securityRules为空/不存在的场景,统一初始化为数组 props[:securityRules] ||= [] # 待追加的安全规则 new_security_rule = { name: 'rule_2', properties: { protocol: 'TCP', sourceAddressPrefix: '*', destinationAddressPrefix: '*', access: 'Allow', destinationPortRange: '22', sourcePortRange: '*', priority: '301', direction: 'Inbound' } } # 向目标数组追加规则 props[:securityRules].push(new_security_rule)
补充说明
- Azure Armrest SDK返回的属性默认使用Symbol(符号)类型作为键,不要用字符串格式的
"securityRules"取值,否则会拿到nil props[:securityRules] ||= []写法会自动判断字段值:字段为空/不存在时自动赋值为空数组,不需要额外写if判断- 本地修改完成后,调用SDK对应的资源更新方法,传入修改后的属性对象即可同步到Azure云端。
内容的提问来源于stack exchange,提问作者user630702
相关产品推荐
相关产品推荐

