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.
I would choose something like this (no sorting needed):
[10, 30, 50, 54, 56, 95, 97, 99].select {|n| n < 52}.max
I think this might work for a sorted array:
[10, 30, 50, 54, 56, 95, 97, 99].sort.reverse.find { |el| el < number }
It just changes the sort direction to descending and finds the first smallest element
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
Use the select option instead of select because choose to iterate over all of your elements. detect returns the first occurrence that matches.
The array does not need to be sorted.
[10, 30, 50, 54, 56, 95, 97, 99].sort { |a, b| b <=> a }.detect { |v| v <= 52 }
Let's assume the array is sorted:
ary = [...] pivot = 52 ary.partition{|n| n < pivot}[0][-1]
You should try rindex
ary.sort.rindex {|el| el < number}
and that return the first matching item.