From: Ben Tilly Date: 2000-12-18T09:51:29+09:00 Subject: [ruby-talk:7526] Re: flatten_by(n) David Alan Black wrote: > >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. Strings turn into arrays of characters? I think I understand why but I still don't really like that. >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.) It it surprising to me that it is faster. IMO += should be just syntactic sugar... > 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.... I didn't contribute much, but it was fun watching. :-) Cheers, Ben _________________________________________________________________ Get your FREE download of MSN Explorer at http://explorer.msn.com