簡體   English   中英

使用文件名創建目錄哈希

[英]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.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM