2014-03-05 72 views
-3

平板阵列我有一个红宝石中hash数组这样递归函数生成分层阵列红宝石

string = "[{\"id\":13},{\"id\":15,\"children\":[{\"id\":16},{\"id\":17,\"children\":[{\"id\":19}]},{\"id\":18}]},{\"id\":14}]" 
hash = Json.parse(string) 

我想创建一个红宝石中hash数组一样:

{13=>nil, 15=>nil, 16=>15, 17=>15, 19=>17, 18=>15, 14=>nil} 
+3

你的问题是什么? – sawa

+0

没有像'Json.parse(字符串)',但'JSON.parse(字符串)'没有工作..'Json.parse(字符串)'会抛出错误。 –

+0

我不明白你的起始字符串/数组如何映射到你的结果。为什么13 =>零但是17 => 15?我根本无法在源字符串中看到它。 –

回答

2

这将做到这一点:

def build_hash(arr, hash={}, parent=nil) 
    return if arr.nil? 
    arr.each do |item| 
    hash[item['id']] = parent 
    build_hash(item['children'], hash, item['id']) 
    end 
    hash 
end 

build_hash(hash) 
# => {13=>nil, 15=>nil, 16=>15, 17=>15, 19=>17, 18=>15, 14=>nil} 
1

我刚刚看到Uri发布他的解决方案,我刚刚完成我的。我在一个哈希上工作,而他的作品在一个数组(你的输入实际上是一个哈希数组,而不是一个哈希)。否则,它们大致相同。我喜欢他稍好,但为了多样性:

@output = {} 
def process(hash, parent=nil) 
    id = hash['id'] 
    children = hash['children'] 
    @output[id] = parent 
    children.each { |child| process(child, id) } unless children.nil? 
end 
hash.each { |h| process(h) } 
p @output 
# => {13=>nil, 15=>nil, 16=>15, 17=>15, 19=>17, 18=>15, 14=>nil} 
+0

OP不说它是一个散列。他们说这是一个散列数组。我也根据阵列提出了与Uri几乎相同的答案,但没有发布,因为这是多余的。在这种情况下,考虑它作为一个数组是更好的,当你看看'[“children”]的值是如何。既然你使用了散列函数,你需要独立于方法调用'hash.each'。 – sawa

+0

@sawa好吧,让我们假设他有点矛盾,因为他命名变量来存储散列数组,'hash' :-) –

+0

我同意这是误导(虽然不矛盾)。我还注意到,OP甚至将期望的结果称为散列数组,当它只是一个散列时。那是错的。 – sawa