Preview Ruby 4.1 is a preview. It can change before the final release. Switch to Ruby 4.0 →
instance method
Array#bsearch_index
() { (Elem element) -> bool? } -> ::Integer?
() { (Elem element) -> ::Numeric? } -> ::Integer?
() -> ::Enumerator[Elem, ::Integer?]
bsearch_index {|element| ... } → integer or nil
bsearch_index → new_enumerator
array.c
View on GitHub ↗
static VALUE
rb_ary_bsearch_index(VALUE ary)
{
rb_len_t low = 0, high = RARRAY_LEN(ary), mid;
int smaller = 0, satisfied = 0;
VALUE v, val;
RETURN_ENUMERATOR(ary, 0, 0);
while (low < high) {
mid = low + ((high - low) / 2);
val = rb_ary_entry(ary, mid);
v = rb_yield(val);
if (FIXNUM_P(v)) {
if (v == INT2FIX(0)) return LEN2NUM(mid);
smaller = (SIGNED_VALUE)v < 0; /* Fixnum preserves its sign-bit */
}
else if (v == Qtrue) {
satisfied = 1;
smaller = 1;
}
else if (!RTEST(v)) {
smaller = 0;
}
else if (rb_obj_is_kind_of(v, rb_cNumeric)) {
const VALUE zero = INT2FIX(0);
switch (rb_cmpint(rb_funcallv(v, id_cmp, 1, &zero), v, zero)) {
case 0: return LEN2NUM(mid);
case 1: smaller = 0; break;
case -1: smaller = 1;
}
}
else {
rb_raise(rb_eTypeError, "wrong argument type %"PRIsVALUE
" (must be numeric, true, false or nil)",
rb_obj_class(v));
}
if (smaller) {
high = mid;
}
else {
low = mid + 1;
}
}
if (!satisfied) return Qnil;
return LEN2NUM(low);
}
Returns the integer index of the element from self found by a binary search, or nil if the search found no suitable element.
See Binary Searching.
Related: see Methods for Fetching.