From: Stefano Crocco Date: 2008-03-03T23:57:36+09:00 Subject: Re: Normal For Loop Alle Monday 03 March 2008, jwmerrill@gmail.com ha scritto: > On Mar 3, 9:37 am, Cory Cory wrote: > > I tried to do this the other night, but right now I can't find a good > > example so here it goes: > > > > a = some_array > > minValue = 999999 > > for(i=0; i > minValue = (5000 - a[i]).abs > > > > } > > What does this example do exactly? It seems to run until it finds a > value in a that is equal to 5000, and then stop without reporting > anything. > > a.detect {|n| 5000 == n} > > or > > a.any? {|n| 5000 == n} > > See, this is actually more concise and readable, I think. > > > This isn't the best example. However, there are many times like the > > loop above where I want to go through the whole thing, but if I find > > exactly what I am looking for, I want to bail out early instead of > > wasting that processing time. > > > > Also, I sometimes may want to not actually iterate straight through, but > > browse through the array in some more complex order. > > The point is not that no examples exist, but that they realistically > don't come up very much. Get familiar with the methods in Enumerable, > Array, and Numeric. Each time you want to write a for loop, try and > use one of those instead, and if you get stuck, ask for advice. > You're solution will almost always be more readable, and maybe 1 time > in 100 you'll need to use a while loop. > > JM If you want to exit the loop before all iterations are done, you can use break. Stefano