2012-08-14 65 views
3

我在數據庫中以JSON格式存在散列。例如從字符串生成嵌套散列並在ruby中深度合併

{ 
    "one" => { 
    "two" => { 
     "three" => {} 
    } 
    } 
} 

我需要從一個字符串中產生這個。上面的例子將由字符串「one.two.three」生成。

首先,我該怎麼做?

問題的第二部分。我會收到多個字符串 - 每個字符串都是最後一個字符串。所以,如果我得到「one.two.three」,然後在「one.two.four」,我哈希是這樣的:

{ 
    "one" => { 
    "two" => { 
     "three" => {}, 
     "four" => {} 
    } 
    } 
} 

如果我得到「one.two.three」兩次,我想要的最新的「三」值可以覆蓋那裏。字符串也可以是任意長度的(例如「one.two.three.four.five」或者「one」)。希望這是有道理的?

+1

只需分割並進行遞歸哈希。網絡上有多個深度合併示例,其中包括一兩個寶石;我可能會首先搜索那些 - 我現在不記得他們的名字。 – 2012-08-14 00:58:59

+0

我會嘗試一些深度合併哈希方法。雖然你是否知道自己的頭頂,如何從「one.two.three」到hash [「one」] [「two」] [「three」]?我知道你可以去「one.two.three」.split(「。」)來獲得數組。 – Plattsy 2012-08-14 01:10:26

回答

13

要生成嵌套的哈希:

hash = {} 

"one.two.three".split('.').reduce(hash) { |h,m| h[m] = {} } 

puts hash #=> {"one"=>{"two"=>{"three"=>{}}}} 

如果您還沒有安裝,然後安裝的ActiveSupport寶石導軌:

gem install activesupport 

然後它列入到您的文件:

require 'active_support/core_ext/hash/deep_merge' 

hash = { 
    "one" => { 
    "two" => { 
     "three" => {} 
    } 
    } 
}.deep_merge(another_hash) 

對內部的訪問將是:

hash['one']['two']['three'] #=> {} 
+0

我不知道deep_merge - 謝謝。你能否給我一個把「one.two.three」轉換爲hash [「one」] [「two」] [「three」]的好方法? – Plattsy 2012-08-14 01:25:37

+0

@Plattsy,看到更新 – megas 2012-08-14 01:29:03

+0

酷感謝那 – Plattsy 2012-08-14 01:31:44