Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

how to find best matching element in array of numbers?

I need help with something that seems simple but confuses me. Trying to write some fuzzy matching method that copes with differences in format between what value is computed as needed, and which are actually available from a selection list.

The value (option strike price) is always a computed Float like 85.0 or Int.

The array contains numbers in string form, unpredictable in either increment or whether they will be shown rounded to some decimal (including extra zeros like 5.50) or no decimal (like 85), eg.:

select_list = ["77.5", "80", "82.5", "85", "87.5", "90", "95", "100", "105"]

I am unsure how to write a simple line or two of code that will return the closest matching element (by number value) as it appears in the array. For example, if select_list.contains? 85.0 returned "85"

Actually, the selection choices come from a Watir::Webdriver browser.select_list(:id, "lstStrike0_1") HTML object whose visible text (not HTML value) are those numbers; maybe there is a more direct way to just call browser.select_list(:id, "lstStrike0_1").select X without having to figure out in Watir how to convert all those choices into a Ruby array?

like image 226
Marcos Avatar asked Jul 13 '12 19:07

Marcos


1 Answers

xs = ["77.5", "80", "82.5", "85", "87.5", "90", "95", "100", "105"]
xs.min_by { |x| (x.to_f - 82.4).abs } 
#=> "82.5"
like image 103
tokland Avatar answered Sep 19 '22 20:09

tokland