Ruby Array #bsearch:当值不在Array中时,操作并返回nil

时间:2016-07-01 04:14:46

标签: ruby performance

我在这里缺少什么?

(我希望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

http://ruby-doc.org/core-2.3.0/Array.html#method-i-bsearch

2 个答案:

答案 0 :(得分:2)

您的语法似乎与文档中的以下内容不符:

  

对于索引小于i的任何元素,该块返回false,   和

     

对于索引大于或的任何元素,块返回true   等于我。

i将永远不会存在于您提供它的块中。例如,在元素11(x = 1)的循环中,对于x< 0>,块将返回false。 i和x> i并且对于每个后续元素也是如此。

您需要将块修改为:

array.bsearch { |x| x >= 11 } # 11
array.bsearch_index { |x| x >= 11 } # 1

在这种情况下,使用相同的示例,对于索引为<的所有元素,块返回false。 1对于索引> = 1

的所有元素都为true

答案 1 :(得分:1)

加勒特约翰逊:

  重要的是   
对于索引小于i的任何元素,该块返回 false   
对于索引大于或等于i的任何元素,该块返回 true

     

如果您的块返回bool,它会找到满足条件的索引最低的元素。

array = [10,11,12,13,14,15]

p array.bsearch_index { |x| 11 - x }
# => 1
p array.bsearch_index { |x| 15 - x }
# => 5

p array.bsearch { |x| 11 - x }
# => 11
p array.bsearch { |x| 15 - x }
# => 15

此解决方案还处理值不在数组

中的情况
p array.bsearch_index { |x| 11.5 - x }
# nil