I've got an array with a list of numbers, e.g.
[10, 30, 50, 54, 56, 95, 97, 99]
If I provide a number e.g. 52, it needs to return the next lowest number in the array, in this case that would be 50.
What's the cleanest way to do this?
Please state if the array must be sorted first.
I'd go for something like this (no need for sorting):
[10, 30, 50, 54, 56, 95, 97, 99].select {|n| n < 52}.max
I think this can work for a sorted array:
[10, 30, 50, 54, 56, 95, 97, 99].sort.reverse.find { |el| el < number }
It simply changes the sorting direction to descending and finds first smaller element
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