| 赞 | 87 |
| VIP | |
| 好人卡 | |
| 积分 | 136 |
| 经验 | |
| 最后登录 | 2021-1-24 |
| 在线时间 | 2753 小时 |
- 梦石
- 0
- 星屑
- 13562
- 在线时间
- 2753 小时
- 注册时间
- 2014-10-4
- 回帖
- 705

|
发表于 2020-6-6 01:11:16
|
显示全部楼层
其实我觉得是有点bug的感觉..
我看了1.8.3的源码
include? 的描述是 对象是否是range的元素之一
但是具体的实现是 对象是否大于下限小于上限 (毕竟一项一项列出来效率太差了)
我感觉可以加个判断 不是同一个类就pass 就没bug了
现在这样 其实就当feature吧 完全不可比较的两个类还是会返回false的反正
而each就是不断succ 所以一定是同一类的
我感觉源码里这段介绍写的超好
我头一次发现Range还能这样写
附上
Range
/* A <code>Range</code> represents an interval---a set of values with a
* start and an end. Ranges may be constructed using the
* <em>s</em><code>..</code><em>e</em> and
* <em>s</em><code>...</code><em>e</em> literals, or with
* <code>Range::new</code>. Ranges constructed using <code>..</code>
* run from the start to the end inclusively. Those created using
* <code>...</code> exclude the end value. When used as an iterator,
* ranges return each value in the sequence.
*
* (-1..-5).to_a #=> []
* (-5..-1).to_a #=> [-5, -4, -3, -2, -1]
* ('a'..'e').to_a #=> ["a", "b", "c", "d", "e"]
* ('a'...'e').to_a #=> ["a", "b", "c", "d"]
*
* Ranges can be constructed using objects of any type, as long as the
* objects can be compared using their <code><=></code> operator and
* they support the <code>succ</code> method to return the next object
* in sequence.
*
* class Xs # represent a string of 'x's
* include Comparable
* attr :length
* def initialize(n)
* @length = n
* end
* def succ
* Xs.new(@length + 1)
* end
* def <=>(other)
* @length <=> other.length
* end
* def to_s
* sprintf "%2d #{inspect}", @length
* end
* def inspect
* 'x' * @length
* end
* end
*
* r = Xs.new(3)..Xs.new(6) #=> xxx..xxxxxx
* r.to_a #=> [xxx, xxxx, xxxxx, xxxxxx]
* r.member?(Xs.new(5)) #=> true
*
* In the previous code example, class <code>Xs</code> includes the
* <code>Comparable</code> module. This is because
* <code>Enumerable#member?</code> checks for equality using
* <code>==</code>. Including <code>Comparable</code> ensures that the
* <code>==</code> method is defined in terms of the <code><=></code>
* method implemented in <code>Xs</code>.
*
*/
|
|