ruby 数组#bsearch : operation and returning nil when value is not in Array

标签 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

最佳答案

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

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/

相关文章:

ruby - 如何在 Windows 7 上运行 ruby​​ 程序?

c++ - 使用多个处理器加速程序

ios - 设置UIImageView图像后多次调用CFRunLoopRun

ruby-on-rails - 未初始化常量 MiniMagick

ruby-on-rails - ActiveScaffold 可以与 Rails 3 一起使用吗?

performance - 为什么这个 Monte Carlo Haskell 程序这么慢?

c++ - 线程与进程

c# - 为什么在 C# 中有些迭代器比其他迭代器快?

ruby-on-rails - f.error_messages仅在基础中显示第一条错误消息

ruby-on-rails - ruby/ruby on rails 内存泄漏检测