tmp = [-3,3,5]
p "test: #{tmp.bsearch_index{|j| j == -3}}"
In the above code, I get response as nil. If I compare j against 3, or 5, it works. Why does bsearch_index does not consider very first element?
tmp = [-3,3,5]
p "test: #{tmp.bsearch_index{|j| j == -3}}"
In the above code, I get response as nil. If I compare j against 3, or 5, it works. Why does bsearch_index does not consider very first element?
Copyright © 2021 Jogjafile Inc.
You need to write
This uses Array#bsearch_index's find minimum mode, which returns the smallest value in the array that satisfies the expression in the block. For example,
In this mode, to quote the doc for Array#bsearch, "the block must always return true or false, and there must be an index
i
(0 <= i <= ary.size
) so that the block returns false for any element whose index is less thani
, and the block returns true for any element whose index is greater than or equal toi
. This method returns thei
-th element. Ifi
is equal toary.size
, it returnsnil
."If the block were
{ |n| n == -3 }
there would be no indexi
,0 <= i <= tmp.size #=> 3
that has the property thattmp[j] == -3
is false for allj < i
and true for allj >= 1
.If the block calculation were
tmp[j] == 5
the requirement would be satisfied (for index2
) so the correct value would be returned. If the block calculation weretmp[j] == 3
the requirement would not be satisfied (tmp[2] == 3 #=> false
); the fact that the correct index is returned is only due to the way the method has been implemented. Ifthen
nil
is returned forn == 3
as well as forn == -3
:bsearch
has a second mode, find any mode. (See the doc forArray#bsearch
for details.) In this case we might write one of the following:This mode would be useful here if
nil
were to be returned when no element in the array evaluates to zero in the block. In other contexts it has a multitude of uses.