I have an array of numbers sorted either in ascending or descending order, and I want to find the index at which to insert a number while preserving the order of the array. If the array is `[1, 5, 7, 11, 51]` and the number to insert is `9`, I would be expecting `3` so I could do `[1, 5, 7, 11, 51].insert(3, 9)`. If the array is `[49, 32, 22, 11, 10, 8, 3, 2]` and the number to be inserted is `9`, I would be expecting `5` so I could do `[49, 32, 22, 11, 10, 8, 3, 2].insert(5, 9)`

What would be the best/cleanest way to find the index at which to insert `9` in either of these two arrays while preserving the sorting of the array?

I wrote this code that works, but it's not very pretty:

```
array = [55, 33, 10, 7, 1]
num_to_insert = 9
index_to_insert = array[0..-2].each_with_index.map do |n, index|
  range = [n, array[index.next]].sort
  index.next if num_to_insert.between?(range[0], range[1])
end.compact.first
index_to_insert # => 3

```