我在这里错过了什么?
(我希望 array.bsearch_index { |x| x == 11 }
等于 1)
array = [10,11,12,13,14,15]
p array.bsearch_index { |x| x == 11 }
# => nil
p array.bsearch_index { |x| x == 15 }
# => 5
p array.bsearch { |x| x == 11 }
# => nil
p array.bsearch { |x| x == 15 }
# => 15
最佳答案
您的语法似乎不符合文档中的以下内容:
the block returns false for any element whose index is less than i, and
the block returns true for any element whose index is greater than or equal to i.
这个 i
永远不会存在于你提供给它的 block 中。例如,在元素 11 (x = 1) 处的循环中,该 block 将对 x <<i
和 x > i
返回 false,并且对于每个后续的元素也是如此。
您需要将 block 修改为:
array.bsearch { |x| x >= 11 } # 11
array.bsearch_index { |x| x >= 11 } # 1
在这种情况下,对于相同的示例,该 block 对索引 < 1 的所有元素返回 false,对索引 >= 1 的所有元素返回 true
关于 ruby 数组#bsearch : operation and returning nil when value is not in Array,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38136948/