On Mon, Dec 03, 2007 at 06:47:18AM +0100, Ryan Davis wrote:
>
> On Dec 2, 2007, at 18:12 , Voroztsov Artem wrote:
>
>> class Array
>>  def flatten2
>>    res = []
>>    x = self.reverse
>>    while !x.empty?
>>      a = x.pop
>>      if a.is_a?(Array)
>>        x.push(*a)
>>      else
>>        res << a
>>      end
>>    end
>>    res.reverse
>>  end
>> end
>
> With that not being recursive, how do you deal with sub-sub-arrays? Hrm... 
> it seems to work. A feature in splat? I'll have to look into that. But:
>
> >> [:a, [:b, [:c], :d], :e].flatten2
> => [:e, :b, :c, :d, :a]
>
I guess quadratic behaviour is caused by appending array over and over
this will work.
class Array
 def flatten3
 	a=[]
	   _flatten3(a)
 end
 def _flatten3(a)
 	each{|i|
		if i.is_a?(Array)
			i._flatten3(a)
		else
			a<<i
		end
	}
 end
end
-- 

The cord jumped over and hit the power switch.