如何在 Ruby 中实现枚举器?
例如:
a = [1,2,3,4,5]
a.delete_if { |x| x > 3 }
相当于:
a = [1,2,3,4,5]
a.delete_if.each.each.each.each { |x| x > 3 }
我知道 a.delete_if 返回一个枚举器。但是,当 each
块返回 true 时,它如何知道应该删除对象呢?如何手动(在 Ruby 中)实现 delete_if
?
For example:
a = [1,2,3,4,5]
a.delete_if { |x| x > 3 }
is equivalent to:
a = [1,2,3,4,5]
a.delete_if.each.each.each.each { |x| x > 3 }
I know a.delete_if
returns an enumerator. But how does it know it should delete object when the each
block returns true? How to implement delete_if
by hand(and in Ruby)?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
你可以看一下Rubinius源代码:可枚举模块
这是拒绝方法的示例:
You can take a look at the Rubinius source code: enumerable module
Here an example of the reject method:
在delete_if的实现中,代码可以验证从yield返回的值来决定是否从数组中删除给定的条目。
您可以阅读《Ruby 编程》指南中的实现迭代器了解更多详细信息,但它看起来像这样:
上面使用
yield
将数组中的每个项目传递到与调用delete_if
关联的块,并隐式返回yield
到外部reject
调用。In the implementation of
delete_if
, the code can verify the value returned fromyield
to decide whether or not to delete the given entry from the array.You can read Implementing Iterators in the Programming Ruby guide for more details, but it would looks something like:
The above uses
yield
to pass each item in the array to the block associated with the call todelete_if
, and implicitly returns the value of theyield
to the outerreject
call.