我如何在Ruby(1.8)中做类似的事情?我的目标是在哈希中为密钥使用变量,我在其中分配变量。
@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|
@keys=@keys+'["'+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 :(得分: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(' ')
产生此输出(即您正在寻找的大哈希和指向所有子路径的指针,最后一个是您所请求的1):
{"long"=>{"keys"=>{"are"=>{"here"=>{"many"=>{"of"=>{"them"=>{"dont"=>{"know"=>{"how"=>{"much"=>{}}}}}}}}}}}}
keysareheremanyofthemdontknowhowmuch areheremanyofthemdontknowhowmuch heremanyofthemdontknowhowmuch manyofthemdontknowhowmuch ofthemdontknowhowmuch themdontknowhowmuch dontknowhowmuch knowhowmuch howmuch much 1