Arrays 在yaml中从Ruby哈希数组中删除元素的最佳方法

Arrays 在yaml中从Ruby哈希数组中删除元素的最佳方法,arrays,ruby,hash,yaml,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中删除键的内容,但是关于从散列数组中删除元素的内容并不多(也许我搜索的是错误的概念?)。对不起,我对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

此解决方案有效,但我丢失了yaml中的所有注释:-(
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]}