Arrays 有什么方法可以让bsearch始终如一地进行相等匹配?
与传递等式一样,传递等式会返回不一致的结果:Arrays 有什么方法可以让bsearch始终如一地进行相等匹配?,arrays,ruby,bsearch,Arrays,Ruby,Bsearch,与传递等式一样,传递等式会返回不一致的结果: [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].bsea
[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
如文档所示,您可以使用=
获得正确的结果;然而,你也会得到:
[0, 4, 7, 10, 12].bsearch {|x| x >= 6 } #=> 7
当您专门寻找6
时,这不是您想要的。如何让它返回一致的结果?要使用bsearch,必须根据块对数组进行排序
查看已映射的块结果,[false,false,true,false,false]
未排序
您的块当前设置为使用“查找最小值”模式,因为它返回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
[0,4,7,10,12].b搜索{x | 7 x}=>7
[0,4,7,10,12].b搜索{| x | 6 x}#=>nil
在本例中,我们使用“comparator”或“spaceship”操作符(
),它返回-1
/0
/1
)
[0, 4, 7, 10, 12].bsearch {|x| 7 <=> x } # => 7
[0, 4, 7, 10, 12].bsearch {|x| 6 <=> x } # => nil