Any way to get bsearch for consistent equality negotiation?

Like an array of samples from documents , equality transfer returns inconsistent results:

[0, 4, 7, 10, 12].bsearch{ |x| x == 4}  # => nil
[0, 4, 7, 10, 12].bsearch{ |x| x == 7}  # => 7
[0, 4, 7, 10, 12].bsearch{ |x| x == 10} # => nil
[0, 4, 7, 10, 12].bsearch{ |x| x == 12} # => 12
[0, 4, 7, 10, 12].bsearch{ |x| x == 0}  # => nil

As the docs show, you can get the correct result with >=; however, you also get:

[0, 4, 7, 10, 12].bsearch {|x| x >= 6 } #=> 7

which is not what you need when you are looking specifically for 6. How do you get it to return consistent results?

+3
source share
1 answer

According to the docs , to use bsearch, your array must be sorted relative to the block.

Looking at the results of your block, [false, false, true, false, false]not sorted.

-, true/false. find-any , -1/0/1.

[0, 4, 7, 10, 12].bsearch {|x| 7 <=> x } # => 7
[0, 4, 7, 10, 12].bsearch {|x| 6 <=> x } # => nil

"" " " (<=>), -1/0/1.

+4

All Articles