Say I have an array of integers:
arr = [0,5,7,8,11,16]
and I have another integer:
n = 6
I need a function that rounds down to the nearest number from the array:
foo(n) #=> 5
As you can see, the numbers do not have a fixed pattern. What's an elegant way to do this?
Thanks
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 }.first
end
E.g:
myarr = [0,5,7,8,11,16]
puts down_to_array 6.5, myarr #=> 5
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With