From: Martin DeMello Date: 2011-05-15T06:33:49+09:00 Subject: Re: search nearest to elements in array (hash) On Sun, May 15, 2011 at 2:58 AM, 7stud -- wrote: > data = [1.1, 4.2, 3.1, 2.6, 6.1, 5.0] > needle = rand 10 > > arr = data.map do |num| >   [(num - needle).abs, num] > end > > sorted = arr.sort_by {|sub_arr| sub_arr[0]} You're sorting when all you want is the minimum data = [1.1, 4.2, 3.1, 2.6, 6.1, 5.0] needle = rand 10 min, mini = nil, 0 data.each_with_index do |num, i| if (num - needle).abs < min min = (num - needle).abs mini = i end end puts "nearest element is #{min} at index #{mini}" martin