From: "Peña, Botp" Date: 2007-10-30T12:19:36+09:00 Subject: Re: find the closest items in an array to a given value. On Behalf Of 7stud --: # a = [ 1.25, 1, 3, 1.9, 1.95, 2.1, 2.2, 1.5] # target = 1.85 # closest_lower = nil # closest_higher = nil # a.each do |elmt| # if elmt < target # if !closest_lower or elmt > closest_lower # closest_lower = elmt # end # elsif elmt > target # if !closest_higher or elmt < closest_higher # closest_higher = elmt # end # else #if elmt == target # #do something # end # end # # Surprisingly, this is slightly faster--even for very large arrays: # target = 1.85 # less_than = [] # greater_than = [] # a.each do |elmt| # if elmt < target # less_than << elmt # # elsif elmt > target # greater_than << elmt # end # end # puts less_than.max # puts greater_than.min cool and straightforward. works in unordered list. 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] in 1.9, there is already group_by, so ~> [(parts=a.group_by{|e| e<=1.85}.values).last.max,parts.first.min] => [1.5, 1.9] ..but we may be working too hard if lists is ordered though. and for ordered lists, a binary search like what ara posted should be the fastest. kind regards -botp