From: David Alan Black Date: 2000-12-18T08:37:22+09:00 Subject: [ruby-talk:7521] Re: flatten_by(n) On Mon, 18 Dec 2000, David Alan Black wrote: > On Mon, 18 Dec 2000, David Alan Black wrote: > > Next iteration: > > def flatten_once > res = [] > for e in self > res.push e if e.nil? > res += e.to_a > end > res > end > I don't know about the rest of you, but I've learned a lot today about how arrays get extended in Ruby :-) The above breaks on empty strings. "".to_a => [], and [1,2,3] + [] == [1,2,3]. So if you have "" in the original array, it will disappear. So -- I'm actually back to something quite similar to Ben's first suggestion, in response to my recursive version, except I'm using concat instead of '+=' because concat is a lot faster. (Surprisingly faster, to me.) def flatten_once res = [] for e in self if e.is_a? Array then res.concat e else res.push e end end res end For the record: 30000 iterations: user system total real 10.330000 0.000000 10.330000 ( 10.327764) # res.concat ... 13.490000 0.000000 13.490000 ( 13.506367) # res += ... And now I really must go do some real work.... David -- David Alan Black home: dblack@candle.superlink.net work: blackdav@shu.edu Web: http://pirate.shu.edu/~blackdav