我有這個散列:如何刪除哈希陣列中的部分?
{"path_1" => [1,2,3], "path_2" => [1,4,5], "path_3" => [1,2,3,4]}
我想從哈希刪除所有「部分」路徑。所以path_1
將需要去,因爲它是path_3
的部分; [1,2,3]
是[1,2,3,4]
的「未完成」數組。所有「部分」需要從這個散列中刪除。
這裏是我當前的代碼的作品,但與大哈希處理時,它的速度慢:
# hash sorted by length of value
hash_array = {"path_1" => [1,2,3], "path_2" => [1,4,5], "path_3" => [1,2,3,4]}
# make a separate copy of the hash
cloned_hash_array = hash_array.clone
hash_array.each {|path_index, path|
# delete this path from the cloned hash so it doesn't match itself
cloned_hash_array.delete(path_index)
cloned_hash_array.each{|cloned_path_index, cloned_path|
if cloned_path[0,path.length] == path.clone
hash_array.delete(path_index)
end
}
}
這僅僅是慣例,但通常多行塊使用'做... end'而不是'{...}'喜歡你正在處理你的每個人。 – 2012-02-01 18:24:04
同意,多行'{...}'塊看起來很奇怪:-) – 2012-02-01 18:25:35
這些數組中的順序是否重要,還是更合適?如果他們是集合,你可以利用Set#proper_subset – DGM 2012-02-01 18:41:48