范围生成中“.."(双点)和“..."(三点)之间的区别? [英] Difference between '..' (double-dot) and '...' (triple-dot) in range generation?

查看:50
本文介绍了范围生成中“.."(双点)和“..."(三点)之间的区别?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我刚刚开始学习 Ruby 和 Ruby on Rails,并遇到了使用范围的验证代码:

I've just started learning Ruby and Ruby on Rails and came across validation code that uses ranges:

validates_inclusion_of :age, :in => 21..99
validates_exclusion_of :age, :in => 0...21, :message => "Sorry, you must be over 21"

起初我认为区别在于包含端点,但在我查看的 API 文档中,它是 .. 还是 .. 似乎并不重要..:它总是包含端点.

At first I thought the difference was in the inclusion of endpoints, but in the API docs I looked into, it didn't seem to matter whether it was .. or ...: it always included the endpoints.

然而,我在 irb 中做了一些测试,它似乎表明 .. 包括两个端点,而 ... 只包括下限而不包括上限一.这是正确的吗?

However, I did some testing in irb and it seemed to indicate that .. includes both endpoints, while ... only included the lower bound but not the upper one. Is this correct?

推荐答案

文档for Range 是这样说的:

使用 .. 构建的范围从头到尾运行.那些使用 ... 创建的不包括最终值.

Ranges constructed using .. run from the beginning to the end inclusively. Those created using ... exclude the end value.

所以 a..b 就像 a <= x <= b,而 a...b 就像 <代码>a <= x .

So a..b is like a <= x <= b, whereas a...b is like a <= x < b.

请注意,虽然整数范围上的 to_a 给出了整数集合,但范围是不是一组值,而只是一对开始/结束值:

Note that, while to_a on a Range of integers gives a collection of integers, a Range is not a set of values, but simply a pair of start/end values:

(1..5).include?(5)           #=> true
(1...5).include?(5)          #=> false

(1..4).include?(4.1)         #=> false
(1...5).include?(4.1)        #=> true
(1..4).to_a == (1...5).to_a  #=> true
(1..4) == (1...5)            #=> false


文档过去不包含此内容,而是需要阅读 Pickaxe 关于范围的部分.感谢@MarkAmery(见下文)注意到此更新.


The docs used to not include this, instead requiring reading the Pickaxe’s section on Ranges. Thanks to @MarkAmery (see below) for noting this update.

这篇关于范围生成中“.."(双点)和“..."(三点)之间的区别?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆