2011-08-25 76 views
2

我怎麼能在Ruby(1.8)中做類似的事情?我的目標是在散列中使用一個變量來分配一個變量。如何在Ruby中使用動態變量名稱嵌套散列?

@keys="" 
my_hash = Hash.new { |h,k| h[k]=Hash.new(&h.default_proc) } 

line="long:keys:are:here:many:of:them:dont:know:how:much" 

line.split(':').each { |x| 
    @[email protected]+'["'+x+'"]' 
} 

my_hash#{@keys}=1 

#I would like to assign a variable for the following. 
# my_hash["long"]["keys"]["are"]["here"]["many"]["of"]["them"]["dont"]["know"]["how"]["many"]=1 
+0

不要使用「動態變量名稱」,而要使用給出的原則。 'hashN [keyN] = valueN'並在解析'hashN + 1 = valueN'的行時構建「鏈」。其他人會用'inject'給出一個小例子,我敢肯定。 – 2011-08-25 17:17:02

+0

你確定這是你想要的嗎?因爲分配給「long:keys:are:here:many:of」會清除它下面的所有內容。如果您確定,請查找「autovivification」(例如,http://stackoverflow.com/search?q=%5Bruby%5D+autovivification) –

+0

Bill,好點。我沒有分享整個代碼,但我想檢查一下密鑰的部分是否已經存在並處理它。 – Istvan

回答

1

循環遍歷項目以嵌套,爲每個項目創建一個新的散列並將其放入先前的散列中。既然你想給最後一個變量分配一個變量,你可以在構建它時保留指向每個變量的指針,一旦你有了它們,你就有一個指向最後一個變量的指針。代碼如下所示:

hash = {} 
line="long:keys:are:here:many:of:them:dont:know:how:much" 

current_depth = hash 
subhash_pointers = [] 
line.split(':').each { |x| 
    current_depth[x] = {} 
    current_depth = current_depth[x] 
    subhash_pointers << current_depth 
} 

puts hash.inspect 

subhash_pointers[-1] = 1 
puts subhash_pointers.join(' ') 

其中產生這樣的輸出(即你正在尋找和指向所有subhashes大哈希,隨着最後一個是1,你的要求):

{"long"=>{"keys"=>{"are"=>{"here"=>{"many"=>{"of"=>{"them"=>{"dont"=>{"know"=>{"how"=>{"much"=>{}}}}}}}}}}}} 

keysareheremanyofthemdontknowhowmuch areheremanyofthemdontknowhowmuch heremanyofthemdontknowhowmuch manyofthemdontknowhowmuch ofthemdontknowhowmuch themdontknowhowmuch dontknowhowmuch knowhowmuch howmuch much 1 
+0

克里斯我不是100%確定我得到了這個權利,但最終你的代碼不會產生與我正在尋找的值的散列。 – Istvan