在ruby中将数组转换为多维哈希的字符串
发布时间:2020-12-17 02:16:56 所属栏目:百科 来源:网络整理
导读:我真的不知道标题是否正确,但问题很简单: 我有一个价值和一把钥匙. 关键如下: “一二三” 现在,我该如何设置这个哈希: params [‘one’] [‘two’] [‘three’] =值 解决方法 您可以尝试使用此代码执行此操作: keys = "one.two.three".split '.' # = ["o
我真的不知道标题是否正确,但问题很简单:
我有一个价值和一把钥匙. 关键如下: “一二三” 现在,我该如何设置这个哈希: 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}}} (编辑:李大同) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |