From: Xavier Noria Date: 2008-09-21T07:57:39+09:00 Subject: Re: for or each? On Sun, Sep 21, 2008 at 12:52 AM, Phlip wrote: > Joe Wölfel wrote: > >> You can try my test if you like. I haven't checked it carefully. But it >> does seem like 'each' is much faster under both ruby 1.86 and ruby 1.9. >> The code is below. > > I just experimented with 'for' and found it does not reevaluate its header > each time it runs. That's the only thing that could have explained the time > difference, so maybe Matz & Co. have simply neglected 'for' while optimizing > .each, which everyone uses. (Though it's still technically superior; not > just an /ad populum/ thing...) > > Another reason to use .each is your collection-like class might override it > to do something cool... There's a technical difference in scopes between them, but for indeed calls #each. A for loop for user in users ... end assumes that users is whatever object that responds to #each, calls the iterator on users and yields the value.