From: Robert Klemme Date: 2007-10-30T06:45:03+09:00 Subject: Re: find the closest items in an array to a given value. On 29.10.2007 21:19, trebor777 wrote: > I'm searching for a light method for finding the closest items to a given > value. > > example/ > > 1..10 > in a range > i give, 5.5, return 5 and 6 for example.... > > as i'm working with arrays, containing numbers, but with no regular step... > it will change i think. > example.. > > a = [ 1, 1.25, 2, 3, 3.5 ] > > if i give 1.85, it gives me 1.25 and 2 It's crucial to know whether your sequence of values is always sorted. If it is, you can use #each_cons and return the pair where left is less-or-equal than x and right is greater-than x. If not, you can just iterate through the array and remember the last match and its distance - overwrite when smaller distance. robert PS: A nice task for #inject. :-)