[英]Creating a directory hash with filename
我有一個文件路徑:
a = "./users/mark/bobapples/Folder/SubFolder/File.txt"
和一個哈希
h = {}
映射哈希中所有目錄的最有效方法是什么,例如:
a.split("/")
=> [".", "users", "mark", "bobapples", "Folder", "SubFolder", "File.txt"]
h["."] = {} if !h["."]
h["."]["users"] = {} if !h["."]["users"]
h["."]["users"]["mark"] = {} if !h["."]["users"]["mark"]
等等。
h={}
a.split("/").reverse.each{|e| h = {e => h.dup}}
h
#=>{"."=>{"users"=>{"mark"=>{"bobapples"=>{"Folder"=>{"SubFolder"=>{"File.txt"=>{}}}}}}}}
h = a.split('/').reverse[1..-1].inject(a.split("/").last) {|memo, o| {o => memo} }
#=> {"."=>{"users"=>{"mark"=>{"bobapples"=>{"Folder"=>{"SubFolder"=>"File.txt"}}}}}}
謝謝@lokson的幫助!
不確定我是否完全理解...。
是這個嗎?
hash=current={};a.split('/')[0..-2].each{|dir| current[dir]={};current=current[dir]}
hash
=> {"."=>{"users"=>{"mark"=>{"bobapples"=>{"Folder"=>{"SubFolder"=>{}}}}}}}
或更短的使用注入:
a.split('/')[0..-2].inject(hash={}){|current,dir| current[dir]={}}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.