https://bugs.ruby-lang.org/
https://bugs.ruby-lang.org/favicon.ico?1711330511
2014-04-29T04:19:12Z
Ruby Issue Tracking System
Ruby master - Bug #9782: Array#bsearch skip first match while using block with complex condition
https://bugs.ruby-lang.org/issues/9782?journal_id=46360
2014-04-29T04:19:12Z
vsyrovat (Valentin Syrovatskiy)
vsyrovat@gmail.com
<ul></ul><p>More accurate description: Array#bsearch cannot find first match while using block with equality condition:</p>
<p>Example:<br>
$ irb<br>
2.1.1 :001 > [1, 2].bsearch{|x| x == 1}<br>
=> nil<br>
(WRONG, expected 1)<br>
2.1.1 :002 > [1, 2].bsearch{|x| x > 0}<br>
=> 1<br>
(Correct)</p>
Ruby master - Bug #9782: Array#bsearch skip first match while using block with complex condition
https://bugs.ruby-lang.org/issues/9782?journal_id=46362
2014-04-29T05:14:42Z
mame (Yusuke Endoh)
mame@ruby-lang.org
<ul><li><strong>Status</strong> changed from <i>Open</i> to <i>Rejected</i></li></ul><p>Array#bsearch is binary search; it works correctly <em>only when</em> the array is sorted.<br>
In other words, "ary.map { cond }" must return [false, false, ..., false, true, true, ..., true] if you want to use "ary.bsearch { cond }".</p>
<blockquote>
<p>[{a:1, b:2}, {a:3, b:4}].bsearch{|x| x[:a] == 1}</p>
</blockquote>
<p>NG, [{a:1, b:2}, {a:3, b:4}].map {|x| x[:a] == 1 } returns [true, false].</p>
<blockquote>
<p>[{a:3, b:4}, {a:1, b:2}].bsearch{|x| x[:a] == 1}</p>
</blockquote>
<p>OK, [{a:3, b:4}, {a:1, b:2}].map {|x| x[:a] == 1} returns [false, true].</p>
<blockquote>
<p>[{a:3, b:4}, {a:1, b:2}].bsearch{|x| x[:a] == 3}</p>
</blockquote>
<p>NG, [{a:3, b:4}, {a:1, b:2}].map {|x| x[:a] == 3} returns [true, false].</p>
<blockquote>
<p>[{a:3, b:4}, {a:1, b:2}].bsearch{|x| x[:b] == 4}</p>
</blockquote>
<p>NG, [{a:3, b:4}, {a:1, b:2}].map {|x| x[:b] == 4} returns [true, false].</p>
<blockquote>
<p>[{a:3, b:4}, {a:1, b:2}, {a:3, b:5}].bsearch{|x| x[:a] == 3}</p>
</blockquote>
<p>NG, [{a:3, b:4}, {a:1, b:2}, {a:3, b:5}].map {|x| x[:a] == 3} returns [true, false, true].</p>
<p>You should use Enumerable#find for your cases.</p>
<p>--<br>
Yusuke Endoh <a href="mailto:mame@tsg.ne.jp" class="email">mame@tsg.ne.jp</a></p>
Ruby master - Bug #9782: Array#bsearch skip first match while using block with complex condition
https://bugs.ruby-lang.org/issues/9782?journal_id=46363
2014-04-29T05:28:25Z
vsyrovat (Valentin Syrovatskiy)
vsyrovat@gmail.com
<ul></ul><p>.</p>
<p>Understood. Thanks for explanation.</p>