我真的不知道标题是否正确,但问题很简单:
我有一个价值和一把钥匙.
关键如下:
“一二三”
现在,我该如何设置这个哈希:
params [‘one’] [‘two’] [‘three’] =值
您可以尝试使用此代码执行此操作:keys = "one.two.three".split '.' # => ["one", "two", "three"] params = {}; value = 1; i = 0; # i is an index of processed keys array element keys.reduce(params) { |hash, key| hash[key] = if (i += 1) == keys.length value # assign value to the last key in keys array else hash[key] || {} # initialize hash if it is not initialized yet (won't loose already initialized hashes) end } puts params # {"one"=>{"two"=>{"three"=>1}}}
精彩评论