Created
February 6, 2009 23:08
-
-
Save greatseth/59673 to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| #!/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