gpt4 book ai didi

ruby - 为什么 `Range#cover?` 在比较失败时不引发异常?

转载 作者:数据小太阳 更新时间:2023-10-29 08:03:12 25 4
gpt4 key购买 nike

鉴于Time对象无法与 Fixnum 进行比较没有显式转换:

0 <= Time.now # => ArgumentError: comparison of Fixnum with Time failed
Time.now <= 10000000000 # => ArgumentError: comparison of Time with 10000000000 failed

什么是documentation for Range#cover? 说,

cover?(obj)true or false

Returns true if obj is between the begin and end of the range.

This tests begin <= obj <= end when exclude_end? is false and begin <= obj < end when exclude_end? is true.

我希望:

(0...10000000000).cover?(Time.now) # => false

引发异常而不是默默返回false .为什么它不引发异常?

可以理解的是,通过显式转换,比较有效:

(0...10000000000).cover?(Time.now.to_i) # => true

最佳答案

该文档没有提及实现细节。 range_cover根据r_less(通过r_cover_p)实现。和 r_less评论说:

/* compares _a_ and _b_ and returns:
* < 0: a < b
* = 0: a = b
* > 0: a > b or non-comparable
*/

这是r_cover_p的来源:

static VALUE
r_cover_p(VALUE range, VALUE beg, VALUE end, VALUE val)
{
if (r_less(beg, val) <= 0) {
int excl = EXCL(range);
if (r_less(val, end) <= -excl)
return Qtrue;
}
return Qfalse;
}

正如我们所见,从任一 r_less 调用返回的正数将导致 Qfalse

现在,我认为文档没有提及它的原因是为了保持简洁。通常(99.9999% 的情况),你应该比较可比较的东西,对吧?在你不这样做的奇怪情况下,你仍然会得到一个正确的答案(“这个时间不属于这个整数范围”)。

关于ruby - 为什么 `Range#cover?` 在比较失败时不引发异常?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35507001/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com