Filter an array by number?
I have an array with a list of numbers, for example.
[10, 30, 50, 54, 56, 95, 97, 99]
If I provide a number for example. 52, it needs to return the next lowest number in the array, in which case it would be 50.
What's the cleanest way to do this?
Indicate whether to sort the array first.
+3
source to share
6 answers
Another way to do it with a sorted array is to use Array#bsearch
on your reverse:
[10, 30, 50, 54, 56, 95, 97, 99].reverse.bsearch { |n| n < 52 } # => 50
+1
source to share