Ruby: Round number down to nearest number based on arbitrary list of numbers Ruby: Round number down to nearest number based on arbitrary list of numbers ruby ruby

Ruby: Round number down to nearest number based on arbitrary list of numbers


Use select followed by max:

arr = [0,5,7,8,11,16]puts arr.select{|item| item < 6}.max

Result:

5

This runs in linear time and doesn't require that the array is sorted.


If you are using relatively small arrays (and so not overly worried about efficiency), then this should work fine:

def down_to_array num, arr  arr.select{|y| y < num}.sort_by{|z| num-z }.firstend

E.g:

myarr = [0,5,7,8,11,16]puts down_to_array 6.5, myarr #=> 5