From: Stefan Rusterholz Date: 2007-10-30T08:25:51+09:00 Subject: Re: find the closest items in an array to a given value. Stefan Rusterholz wrote: > trebor777 wrote: >> Hi! >> >> I'm searching for a light method for finding the closest items to a >> given >> value. > > [1,2,3,4,5,6].min { |a,b| (a-value).abs <=> (b-value).abs } > > Regards > Stefan Since you want more than 1 you can either implement your own min method that returns the 2 smallest ones, that'd happen in O(n), or you can sort by the distance, which is O(nlogn): ary.sort_by { |item| (value-item).abs }.first(n) If you just want all values that are a max difference of x from y, you can use: ary.select { |item| item - x <= y } Regards Stefan -- Posted via http://www.ruby-forum.com/.