From: 7stud -- Date: 2007-10-30T14:37:14+09:00 Subject: Re: find the closest items in an array to a given value. Pe単a, Botp wrote: > have you tried #partition? > > ~> a > => [1.25, 1, 3, 1.9, 1.95, 2.1, 2.2, 1.5] > ~> [(parts=a.partition{|i| i<=1.85}).first.max,parts.last.min] > => [1.5, 1.9] > No, I haven't. Thanks for pointing the partition method out to me. I must have been testing my first method on a different, longer array because now it runs slightly faster than my second method, as well as the partition solution, which makes more sense to me. Here are the results I get: test1 exec time(1,000,000 loops): 10.348911 total test2 exec time(1,000,000 loops): 13.916226 total test4 exec time(1,000,000 loops): 12.912649 total where test4 is this code: a = [ 1.25, 1, 3, 2, 3.5, 4.25, 0.65, 1.5, 7.7, 9.2] target = 1.85 arr = a.partition do |elmt| elmt < target end closest_lower = arr[0].max closest_higher = arr[1].min end But they are all pretty much equivalent. inject() is so slow, I just hit ctrl-c after what seems like 5 minutes. -- Posted via http://www.ruby-forum.com/.