--nextPart1391113.to4lkFZHQv Content-Type: text/plain; charset="utf-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 array= s : > >=20 > > zl =3D 9 if farthest_proposition.distance_to(origin) < =3D 25.0 > > zl =3D 10 if farthest_proposition.distance_to(origin) <=3D 15.0 > > zl =3D 11 if farthest_proposition.distance_to(origin) <=3D 10.0 > > zl =3D 12 if farthest_proposition.distance_to(origin) <=3D 5.0 > > zl =3D 13 if farthest_proposition.distance_to(origin) < =3D2.0 > > zl =3D 14 if farthest_proposition.distance_to(origin) <=3D 1.0 > >=20 > > how could I replace it the dryest way possible ? > >=20 > > zl =3D [9, 10, 11, 12, 13, 14] > > distance =3D [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 >=20 > 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. >=20 > Assuming two arrays given above are called ZL and DISTANCE (they should > really be constants), one solution is: >=20 > farthest_distance =3D farthest_proposition.distance_to(origin) > zl =3D DISTANCE.zip(ZL.reverse).find { |distance, _| > farthest_distance <=3D distance > }.first >=20 > 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: >=20 > # (distance, z1) sorted by distance > ZL_BY_DISTANCE =3D [ > [ 1.0, 14 ], > [ 2.0, 13 ], > [ 5.0, 12 ], > [ 10.0, 11 ], > [ 15.0, 10 ], > [ 25.0, 9 ] > ] >=20 > ...at which point you could simply write: >=20 > farthest_distance =3D farthest_proposition.distance_to(origin) > zl =3D ZL_BY_DISTANCE.find { |distance, _| > farthest_distance <=3D distance > }.first >=20 > (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.) >=20 > -mental Anyone doing any sort of programming should be using a font that distinguis= hes=20 1 and l. Sorry if that sounds a bit harsh, but using a good font is important. Regards, =2D-=20 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= =+ePt -----END PGP SIGNATURE----- --nextPart1391113.to4lkFZHQv--