在yaml中从Ruby散列数组中删除元素的最佳方法

时间:2015-10-05 21:44:55

标签: arrays ruby hash yaml

我在网上看到很多关于从yaml删除密钥的内容,但是从哈希数组中删除元素并不多(可能我在搜索错误的概念?)。对不起,我对Ruby或其他任何编程都很陌生。

我尝试从yaml文件中删除特定端口,而不实际删除IP本身或其余任何数组值。

require 'yaml'
ip = 1.2.3.4
port = 3333

hash = YAML.load_file('ips.yml')
hash.delete([ip][port])
File.open('ips.yml','w'){|f| YAML.dump(hash,f)}

yaml文件

---
69.39.239.151:
- 7777
- 8677
- 8777
69.39.239.75:
- 9677
- 9377
209.15.212.147:
- 8477
- 7777
104.156.244.109:
- 9999
1.2.3.4:
- 3333
- 4444

1 个答案:

答案 0 :(得分:1)

require 'yaml'
ip = '1.2.3.4'
port = 3333

hash = YAML.load_file('ips.yml')
puts "hash (before): #{hash.inspect}"
hash[ip].delete(port) # here you are deleting the port (3333) from the ip (1.2.3.4)
puts "hash (after): #{hash.inspect}"
File.open('ips.yml', 'w') { |f| YAML.dump(hash, f) }

# hash (before): {"69.39.239.151"=>[7777, 8677, 8777], "69.39.239.75"=>[9677, 9377], "209.15.212.147"=>[8477, 7777], "104.156.244.109"=>[9999], "1.2.3.4"=>[3333, 4444]}
# hash (after): {"69.39.239.151"=>[7777, 8677, 8777], "69.39.239.75"=>[9677, 9377], "209.15.212.147"=>[8477, 7777], "104.156.244.109"=>[9999], "1.2.3.4"=>[4444]}