Ruby 2.0.0 Array#bsearch behavior

后端 未结 2 2024
心在旅途
心在旅途 2020-12-15 06:35

I noticed that as of Ruby 2.0.0 the array class has a bsearch method that I was testing and I\'m not getting the behavior I\'d expect. Why does it return a val

2条回答
  •  失恋的感觉
    2020-12-15 06:36

    I find it more intuitive to use the spaceship operator

    array.bsearch {|x| 3 <=> x }
    

    Just make sure to put the x to the right of the spaceship.

    The reason why is that the thing being compared against during each iteration is the left-hand operand. So if you want to find a 3, you need to continually compare against a 3, in order to get the correct left, right, or equal result. If you put the variable on the left (as one might intuitively to do), you've reversed the comparison output, foiling the bsearch algorithm!

    This also works for strings and any object that is comparable with <=>.

提交回复
热议问题