From: Niklas Frykholm Date: 2002-06-07T07:33:28+09:00 Subject: Re: Unflatten [Shashank Date]: > I am trying to convert a flat list (array) of tokens into a nested list > (hence the name UNflatten) using a simple rule: > Every token which looks like '(' begins a nested list and the corresponding > ')' token ends it ... in a recursive fashion. > e.g: > ["a", "(","b", ")"] ==> ["a",[ "b" ]] > [ "(", "a", "(","b", ")", ")"] ==> [["a",["b"]]] My suggestions: def unflatten(list, left='(', right=')') current = [] stack = [] list.each do |x| if x == left stack << (current << []) current = current[-1] elsif x == right raise "unbalanced" if stack.size == 0 current = stack.pop else current << x end end raise "unbalanced" unless stack.size == 0 return current end def reflatten(list, left='(', right=')') acc = [] list.each do |x| if Array === x acc << left acc += reflatten(x, left, right) acc << right else acc << x end end return acc end // Niklas