Array#bsearch in Ruby returns nil 如果0索引值是唯一满足条件的值
Array#bsearch in Ruby returns nil if the 0 index value is the ONLY value that meets the condition
我在下面提供了测试用例,这只是一个满足我好奇心的问题。
Array#bsearch
的 ruby 文档说:
"这个方法returns第i个元素。如果i等于ary.size,它returns nil。"
我还没有完全理解这个解释。有人可以更深入地解释一下吗?
def greater_than_8(ary)
a = ary.bsearch { |x| x.to_f > 8 }
a.nil? || a.to_f < 8 ? "No number greater than 8" : a
end
ary = [0, 4, 7, 10, 12]
puts greater_than_8(ary)
#=> 10
# Shouldn't this return 14?
ary = [14, 3, 7]
puts greater_than_8(ary)
#=> "No number greater than 8"
# THERE IT IS!
ary = [14, 13, 7]
puts greater_than_8(ary)
#=> 14
ary = [8, 8, 8, 8]
puts greater_than_8(ary)
#=> "No number greater than 8"
ary = [8.01, 123]
puts greater_than_8(ary)
#=> 8.01
ary = ["one hundred", "151", "120", 9]
puts greater_than_8(ary)
#=> 151
欢迎来到堆栈溢出!二分查找的前提是要查找的列表必须是有序的,而 [14, 3, 7]
不是。在排序版本 ([3, 7, 14]
) 上调用您的函数应该会产生您期望的结果。
the elements of the array must be monotone (or sorted) with respect to the block.
Array#bsearch
的部分文档要求如下:
You can use this method in two modes: a find-minimum mode and a find-any mode. In either case, the elements of the array must be monotone (or sorted) with respect to the block.
在您的示例中,您使用的是查找最小值模式。从那里我们会查看您使用过的一些输入,看看它们是否单调。
# Monotone increasing, allowed
ary = [0, 4, 7, 10, 12]
# Not monotone, not allowed
ary = [14, 3, 7]
# Monotone decreasing, allowed
ary = [14, 13, 7]
我在下面提供了测试用例,这只是一个满足我好奇心的问题。
Array#bsearch
的 ruby 文档说:
"这个方法returns第i个元素。如果i等于ary.size,它returns nil。"
我还没有完全理解这个解释。有人可以更深入地解释一下吗?
def greater_than_8(ary)
a = ary.bsearch { |x| x.to_f > 8 }
a.nil? || a.to_f < 8 ? "No number greater than 8" : a
end
ary = [0, 4, 7, 10, 12]
puts greater_than_8(ary)
#=> 10
# Shouldn't this return 14?
ary = [14, 3, 7]
puts greater_than_8(ary)
#=> "No number greater than 8"
# THERE IT IS!
ary = [14, 13, 7]
puts greater_than_8(ary)
#=> 14
ary = [8, 8, 8, 8]
puts greater_than_8(ary)
#=> "No number greater than 8"
ary = [8.01, 123]
puts greater_than_8(ary)
#=> 8.01
ary = ["one hundred", "151", "120", 9]
puts greater_than_8(ary)
#=> 151
欢迎来到堆栈溢出!二分查找的前提是要查找的列表必须是有序的,而 [14, 3, 7]
不是。在排序版本 ([3, 7, 14]
) 上调用您的函数应该会产生您期望的结果。
the elements of the array must be monotone (or sorted) with respect to the block.
Array#bsearch
的部分文档要求如下:
You can use this method in two modes: a find-minimum mode and a find-any mode. In either case, the elements of the array must be monotone (or sorted) with respect to the block.
在您的示例中,您使用的是查找最小值模式。从那里我们会查看您使用过的一些输入,看看它们是否单调。
# Monotone increasing, allowed
ary = [0, 4, 7, 10, 12]
# Not monotone, not allowed
ary = [14, 3, 7]
# Monotone decreasing, allowed
ary = [14, 13, 7]