我真的不知道标题是否正确,但问题很简单:
我有一个值和一个键。
密钥如下:
"one.two.three"
现在,我如何设置这个散列:
params['one']['two']['three'] = value
发布于 2012-01-26 17:37:26
您可以尝试使用以下代码来完成此操作:
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}}}发布于 2012-01-26 19:56:02
使用递归:
def make_hash(keys)
keys.empty? ? 1 : { keys.shift => make_hash(keys) }
end
puts make_hash("one.two.three".split '.')
# => {"one"=>{"two"=>{"three"=>1}}}发布于 2012-01-26 20:04:16
您可以使用inject方法:
key = "one.two.three"
value = 5
arr = key.split(".").reverse
arr[1..-1].inject({arr[0] => value}){ |memo, i| {i => memo} }
# => {"one"=>{"two"=>{"three"=>5}}}https://stackoverflow.com/questions/9015977
复制相似问题