如何在 Ruby 中使用嵌套哈希的动态变量名称?
我怎样才能在 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
How could I do something similar in Ruby (1.8)? My aim is to use a variable for the key in the hash where I assign a variable.
@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
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
循环遍历要嵌套的项目,为每个项目创建一个新的哈希值并将其放入前一个哈希值中。由于您想为最后一个变量分配一个变量,因此您可以在构造变量时保留指向每个变量的指针,一旦拥有所有变量,您就拥有了指向最后一个变量的指针。代码如下所示:
产生以下输出(即您正在查找的大哈希值和指向所有子哈希值的指针,最后一个根据您的要求为 1):
Loop through the items to nest through, creating a new hash for each and putting it inside the previous hash. Since you want to assign a variable to the last one, you can keep pointers to each as you construct it and once you have them all, you have a pointer to the last one. The code looks like this:
Which produces this output (namely the big hash you were looking for and pointers to all the subhashes, with the last one being 1 as you requested):