From: MenTaLguY Date: 2007-10-31T03:41:09+09:00 Subject: Re: RUBY DRY to replace 6 lines in 1 On Wed, 31 Oct 2007 01:50:08 +0900, Josselin 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