Ruby Array#bsearch_index
bsearch_index in find-minimum mode returns the first index where a monotonic boolean predicate becomes true.
A simple example
Array#bsearch_index
- Start with Sorted values 1, 3, 5
- Do this Find the first value at least 2
- Result 3
Syntax
index = sorted.bsearch_index { |value| value >= target }
Run this example in Ruby
Save the program as lesson.rb. Use Ruby 2.6 or later.
ruby lesson.rb
Find the first threshold that covers a price
A price catalog is already sorted and can contain repeated thresholds. Locate the correct boundary and check what the returned position means when an exact value is absent.
tiers = [10, 20, 20, 40]
[20, 50].each do |target|
index = tiers.bsearch_index { |value| value >= target }
puts index.nil? ? 'no tier' : index
end
1 no tier
A sorted ascending array makes this predicate monotonic. If every threshold falls below the target, the lookup returns nil.
Ruby documentation for Array#bsearch_index
Locate a numbered tote
A parcel clerk keeps tote numbers in ascending order. Find the specified item in the sorted register. How many smaller entries come before it?
Find the earliest permit
A permit clerk starts with the smallest valid identifier. Find the specified item in the sorted register. How many smaller entries come before it?