1
tmp = [-3,3,5]
p "test: #{tmp.bsearch_index{|j| j == -3}}"

在上面的代码中,我得到的响应为零。如果我将 j 与 3 或 5 进行比较,它会起作用。为什么 bsearch_index 不考虑第一个元素?

4

1 回答 1

3

你需要写

tmp.bsearch_index{|n| n >= -3}    #=> 0

这使用Array#bsearch_index查找最小值模式,该模式返回数组中满足块中表达式的最小值。例如,

tmp.bsearch { |n| n >= 0 }        #=> 3
tmp.bsearch_index { |n| n >= 0 }  #=> 1

在这种模式下,引用Array#bsearch的文档,“块必须始终返回 true 或 false,并且必须有一个索引i( 0 <= i <= ary.size),以便块对于索引小于的任何元素返回 false i,并且块返回对于索引大于或等于的任何元素为真i。此方法返回第i-th 元素。如果i等于ary.size,则返回nil

如果块{ |n| n == -3 }没有索引i0 <= i <= tmp.size #=> 3则它具有tmp[j] == -3对所有为假j < i且对所有为真的属性j >= 1

如果块计算是tmp[j] == 5满足要求(对于 index 2),那么将返回正确的值。如果块计算tmp[j] == 3不满足要求(tmp[2] == 3 #=> false);返回正确索引的事实仅取决于方法的实现方式。如果

tmp = [-3, 3, 5, 6]

thennil返回 forn == 3和 for n == -3

tmp.bsearch_index { |n| n == 3 }  #=> nil

bsearch有第二种模式,找到任何模式。(有关详细信息,请参阅文档Array#bsearch。)在这种情况下,我们可能会编写以下内容之一:

tmp.bsearch_index { |n| -3 - n }  #=> 0   
tmp.bsearch_index { |n|  3 - n }  #=> 1
tmp.bsearch_index { |n|  5 - n }  #=> 2
tmp.bsearch_index { |n|  4 - n }  #=> nil

nil如果在数组中没有元素在块中计算为零时返回此模式,则此处将很有用。在其他情况下,它有多种用途。

于 2020-07-30T21:30:07.330 回答