--------------enig18F22A83D32FDC77DB83D69C Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: quoted-printable Cory Cory wrote: [for-loops instead of Array#each and friends] > a = some_array > minValue = 999999 > for(i=0; i<a.length && minValue!=0; i+=1) { > minValue = (5000 - a[i]).abs > } > Break is your friend; Some solutions for this example: # No. 1 # (assuming that you are going to process the element, in this case, # printing it to STDOUT and adding a newline): a = [100, 200, 3000, 5000, 80000] # Arbitrary Array initialisation, # will be needed for all examples. a.each {|i| break if (5000-i).abs == 0 puts i } 100 200 3000 ==>nil # No. 2 # returning an array with elements *not* meeting the condition a.reject { |i| (5000-i).abs == 0 } # Can also be used as 'select' # with inverted condition ==>[100, 200, 3000, 80000] # No. 3 # returning an array without elements > 5000 a.select { |i| i < 5000 } ==>[100, 200, 3000] # No. 4 # contrived example, using #map and #compact # Warning: Don't try this at home a.map { |i| i < 5000 ? i : nil }.compact ==>[100, 200, 3000] # No. 5 # contrived example again, this time using 'size' and artificial # 'index'; using exact condition, so 'unless' is needed instead of # 'if'. Using puts for 'debug' messages, or instead of processing # values. Less readable. a.size.times { |i| break unless (5000 - a[i]).abs != 0 puts a[i] } 100 200 3000 ==>nil > > 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. That's what 'break' is for. > > Also, I sometimes may want to not actually iterate straight through, but > browse through the array in some more complex order. For Array manipulation, selection etc, refer to 'ri Array' - I can't see how 'C-style for loops' would help there either. t. -- Anton Bangratz - Key ID 363474D1 - http://tony.twincode.net/ fortune(6): Signs of crime: screaming or cries for help. -- The Brown University Security Crime Prevention Pamphlet --------------enig18F22A83D32FDC77DB83D69C Content-Type: application/pgp-signature; name="signature.asc" Content-Description: OpenPGP digital signature Content-Disposition: attachment; filename="signature.asc" -----BEGIN PGP SIGNATURE----- Version: GnuPG v1.4.6 (GNU/Linux) Comment: Using GnuPG with Mozilla - http://enigmail.mozdev.org iQEVAwUBR8wWEQgZMsE2NHTRAQL50wgAng1uCqeyxsFxZ0nZobaIHR/VuCdv/kYB 5E3KJCnF0Y/67jtT374e0w5JjlK/C2qfkBG0gXg/FY50mwnXsqG+IC4R2V/1ezMs vJ+Z5rIgb5qiPdcmnCCxGAARepAEiS5Ykg92oCXhWSwpszFHKzaFMhjPCGErP7fm G0m+ho8XLSiDCBw2RPbF+Z1T6lHp538htn++MyzpM/e+WWfiU2g9kHCt1+N4Uplf Exb+r1AmUtGIG4DFWX5+EwMuASqeurD4gdEL3nml01367EDrNyfQ62pTitYC9Ya7 Pwd+ygZQsiK39pwaRUs0CKAMwGazjFRe2YdbYnvGLDpyy284wxecFQ a -----END PGP SIGNATURE----- --------------enig18F22A83D32FDC77DB83D69C--