2015-10-05 341 views
1

我在網上看到很多關於從yaml中刪除的信息,但是從哈希數組中刪除元素並不多(可能我正在尋找錯誤的概念?) 。對不起,我對Ruby很陌生,或者對於這個問題的任何編程。從yaml中刪除元素的最佳方法

我試圖從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
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]} 
相關問題