From: Park Heesob Date: 2002-06-07T10:53:44+09:00 Subject: Re: Unflatten Hi, "Niklas Frykholm" wrote in message news:slrnafvnam.s4k.r2d2@shaka.acc.umu.se... > [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 > Simple but awful solution. def unflatten(list) eval list.inspect.gsub(/"\(",/ , '[').gsub(/"\)"/ , ']') end Park Heesob.