Ruby 中 Point 类的高级特性与实现
1. 枚举坐标
如果一个 Point 对象能像包含两个元素的数组那样工作,那么我们应该可以像遍历真正的数组一样遍历这些元素。以下是为 Point 类定义的 each 迭代器:
# This iterator passes the X coordinate to the associated block, and then
# passes the Y coordinate, and then returns. It allows us to enumerate
# a point as if it were an array with two elements. This each method is
# required by the Enumerable module.
def each
yield @x
yield @y
end
定义了这个迭代器后,我们可以编写如下代码:
p = Point.new(1,2)
p.each {|x| print x } # Prints "12"
更重要的是,定义 each 迭代器使我们能够混入 Enumerable 模块的方法,这些方法都是基于 each 定义的。通过添加一行代码,我们的类就能获得 20 多个迭代器:
超级会员免费看
订阅专栏 解锁全文
63

被折叠的 条评论
为什么被折叠?



