Josselin
2/17/2007 4:16:00 PM
On 2007-02-17 17:09:32 +0100, Stefan Rusterholz <apeiros@gmx.net> said:
> Josselin wrote:
>> I need to produce such array :
>>
>> root = ["22", "friend 22", ["11", "contact 11", [ ] ] , ["13",
>> "contact 13"], ["17", "contact 17"]]
>> writing
>>
>> root[0] = friend.id_to_s
>> root[1] = friend.pseudo
>>
>> then for each friend.contact , I write an array
>> friend_array[0] = contact.id.to_s
>> friend_array[1] = contact.pseudo
>> ... then I would like to write
>> friend_array[2] = [�] if contact.info.count > 0
>> .. I need to write an empty array in this case... (otherwise there is
>> no friend_array[2] )
>>
>> how can I write it ?
>>
>> tfyl
>>
>> joss
>
> Either recursively or iteratively with a stack.
> def append_friends(append_to, friends)
> friends.each { |contact|
> as_array = [contact.id.to_s, contact.pseudo, []]
> append_friends(as_array[2], contact.friends)
> append_to[2] << as_array
> }
> append_to
> end
>
> There are probably nicer ways to write the recursive variant. Feel free
> to evolve it.
>
> Iterative version is left as an exercise to the reader ;-) (with ruby
> the iterative variant of this
> is most probably quite a bit faster btw.)
>
> My regards
thanks a lot ! that's great... I'll try to find a recursive variant later..
joss