Skip to content

Instantly share code, notes, and snippets.

@greatseth
Created February 6, 2009 23:08
Show Gist options
  • Select an option

  • Save greatseth/59673 to your computer and use it in GitHub Desktop.

Select an option

Save greatseth/59673 to your computer and use it in GitHub Desktop.
#!/usr/bin/env ruby
class Array
def nearest_to(given)
if given < min
min
elsif given > max
max
else
low, high = map do |r|
[r, self[index(r)+1]]
end.detect { |x,y| y and (x..y).include?(given) }
up = high - given
down = given - low
(up <= down) ? high : low
end
end
end
list = [1,5,20]
puts "list is #{list.inspect}"
[0,2,3,7,15,30].each do |given|
puts "nearest to #{given}: #{list.nearest_to given}"
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment