如何在Ruby中使用动态变量名称嵌套散列?

问题描述:

我怎么能在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://*.com/search?q=%5Bruby%5D+autovivification) –

+0

Bill,好点。我没有分享整个代码,但我想检查一下密钥的部分是否已经存在并处理它。 – Istvan

循环遍历项目以嵌套,为每个项目创建一个新的散列并将其放入先前的散列中。既然你想给最后一个变量分配一个变量,你可以在构建它时保留指向每个变量的指针,一旦你有了它们,你就有一个指向最后一个变量的指针。代码如下所示:

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