加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 百科 > 正文

Ruby的“===”操作符在范围上的含义

发布时间:2020-12-16 22:02:49 所属栏目:百科 来源:网络整理
导读:我最近开始学习 Ruby,我正在阅读下面的 Ruby Manual. 在本手册中,他们说如下(关于范围): A final use of the versatile range is as an interval test: seeing if some value falls within the interval represented by the range. This is done using ===,
我最近开始学习 Ruby,我正在阅读下面的 Ruby Manual.

在本手册中,他们说如下(关于范围):

A final use of the versatile range is as an interval test: seeing if
some value falls within the interval represented by the range. This is
done using ===,the case equality operator.

有了这些例子:

>(1..10)=== 5?true
>(1..10)=== 15?虚假
>(1..10)=== 3.14159?真的
>(‘a’..’j’)===’c’?true
>(‘a’..’j’)===’z’?false

在阅读了关于Ruby的“===”运算符here之后,我发现这在范围上有效,因为Ruby将其转换为case语句.

So you may want to be able to put the range in your case statement,
and have it be selected. Also,note that case statements translate to
b===a in statements like case a when b then true end.

但是我有以下问题:为什么以下命令返回true?

(1..10)=== 3.14159?真的

由于(1..10)是指[1,2,3,4,5,6,7,8,9,10],我预计结果是假的.

解决方法

在数学意义上,1..10表示从0到10的 Range,因此包含3.14259

与[1,10]不同.

该数组是方法Range#each的结果,由Enumerable#to_a用于构造对象的数组表示,仅产生包含的整数值在范围内,由于产生所有实际值将意味着遍历无数个元素.

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读