--nextPart1391113.to4lkFZHQv Content-Type: text/plain; charset tf-8" Content-Transfer-Encoding: quoted-printable Content-Disposition: inline Quoth MenTaLguY: > On Wed, 31 Oct 2007 01:50:08 +0900, Josselin <josselin / wanadoo.fr> wrote: > > I have a group of lines (used in Googlemaps display) based on 2 arrays : > > > > zl = 9 if farthest_proposition.distance_to(origin) < = 25.0 > > zl = 10 if farthest_proposition.distance_to(origin) <= 15.0 > > zl = 11 if farthest_proposition.distance_to(origin) <= 10.0 > > zl = 12 if farthest_proposition.distance_to(origin) <= 5.0 > > zl = 13 if farthest_proposition.distance_to(origin) < =2.0 > > zl = 14 if farthest_proposition.distance_to(origin) <= 1.0 > > > > how could I replace it the dryest way possible ? > > > > zl = [9, 10, 11, 12, 13, 14] > > distance = [1.0, 2.0, 5.0, 10.0, 15.0, 25.0] > > farthest_proposition.distance_to(origin) is never > 25 (eliminated > > before..) > > farthest_proposition.distance_to(origin) can be 0.0, never negative > > FWIW, one line isn't necessarily a realistic goal; DRY doesn't always > mean a large savings in LOC, just maintainability (which an excessively > "golfed" solution can hurt) and often performance. > > Assuming two arrays given above are called ZL and DISTANCE (they should > really be constants), one solution is: > > farthest_distance = farthest_proposition.distance_to(origin) > zl = DISTANCE.zip(ZL.reverse).find { |distance, _| > farthest_distance <= distance > }.first > > Note that eliminating the repeated calls to #distance_to will yield > a performance increase. You could also gain additional performance > by combining ZL and DISTANCE into an associative list: > > # (distance, z1) sorted by distance > ZL_BY_DISTANCE = [ > [ 1.0, 14 ], > [ 2.0, 13 ], > [ 5.0, 12 ], > [ 10.0, 11 ], > [ 15.0, 10 ], > [ 25.0, 9 ] > ] > > ...at which point you could simply write: > > farthest_distance = farthest_proposition.distance_to(origin) > zl = ZL_BY_DISTANCE.find { |distance, _| > farthest_distance <= distance > }.first > > (Side note: you might want to consider avoiding lower-case l in > variable names if you can; it is hard to tell apart from the number 1 > in many fonts.) > > -mental Anyone doing any sort of programming should be using a font that distinguishes 1 and l. Sorry if that sounds a bit harsh, but using a good font is important. Regards, -- Konrad Meyer <konrad / tylerc.org> http://konrad.sobertillnoon.com/ --nextPart1391113.to4lkFZHQv Content-Type: application/pgp-signature; name=signature.asc Content-Description: This is a digitally signed message part. -----BEGIN PGP SIGNATURE----- Version: GnuPG v1.4.7 (GNU/Linux) iD8DBQBHJ4E1CHB0oCiR2cwRAtHXAJ46Vb3ofOVKCoFq7SsECYOVWEGh+gCgyLGV Wy2lmkj9rZuJhnmJWjrfE3oミ ュュュュュナホト ミヌミ モノヌホチヤユメナュュュュュ ュュミアウケアアアウョエニレネムュュ