Thursday 15 April 2010

How to recursively build nested json/hash pairs in ruby? -


I have a list of Rabbi hash objects (I finally convert them to Jason) I have to change the nested pair. Appear in the list. Therefore, if I have

  aa = [[[name = & gt; "Which"}, {: type = & gt; "Normal"}, {: animal = & gt; "Dog"}, {: age = & gt; 5}, {a: 1}, {b: 2}, {c: 3}, {d: 4}]  

I need to make changes in:

  {: first = & gt; {: First = & gt; {: First = & gt; {: Name = & gt; "Joe"} ,: Second = & gt; {: Type = & gt; "Normal"}},: second = & gt; {: First = & gt; {: Animal = & gt; "Dog"},: second = & gt; {: Age = & gt; 5}}},: second = & gt; {: First = & gt; {: First = & gt; {A: 1} ,: Second = & gt; {B: 2}} ,: Second = & gt; {: First = & gt; {C: 3} ,: Second = & gt; {D: 4}}}  

This input can be necessarily nested according to the length of the list.

I am completely emptying how I can repeat it like a balanced binary tree where the data is only on the leaves I can not find an algorithm that is specially Doing so, I also read about B + trees, but it is not binary and balanced.

As always, I feel that I am missing some simple and obviously some kind of ruby ​​/ jsn functionality has been built, am I missing?

You can do this (note that I added an element {e: 5} the number of hash will not have the power of two):

  arr = [{name: "joe"}, {type: "normal"}, {animal: "dog"} , {Age: 5}, {a: 1}, {b: 2}, {c: 3}, {d: 4}, {E: 5}] def hashish (ar) returns arr firstly if arr.size == 1 half = (arr.size + 1) / 2 {first: hash line (arr [0, half])). Merge (second: hashish (arr [half ..-1])) hash ify (ARI) # = & gt; {: First = & gt; # {: First = & gt; # {: First = & gt; {: First = & gt; # {: Name = & gt; "Joe"} ,: second = & gt; {: Type = & gt; "Normal"} #, #: seconds = & gt; {: Animal = & gt; "Dog"} #, #: seconds = & gt; # {: First = & gt; {: Age = & gt; 5} ,: seconds = & gt; {: A = & gt; 1}} #}, #: seconds = & gt; # {: First = & gt; # {: First = & gt; # {: B = & gt; 2} ,: seconds = & gt; {: C = & gt; 3}}, #: seconds = & gt; # {: First = & gt; {: D = & gt; 4} ,: seconds = & gt; {E = & gt; 5}} #} #}  

No comments:

Post a Comment