[英]How to implement an enumerator in Ruby?
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. 我知道a.delete_if
返回一个枚举器。 But how does it know it should delete object when the each
block returns true? 但是,当each
块返回true时,它如何知道它应该删除对象? How to implement delete_if
by hand(and in Ruby)? 如何手动(以及在Ruby中)实现delete_if
?
You can take a look at the Rubinius source code: enumerable module 您可以查看Rubinius源代码: 枚举模块
Here an example of the reject method: 这里是拒绝方法的一个例子:
def reject
return to_enum(:reject) unless block_given?
ary = []
each do |o|
ary << o unless yield(o)
end
ary
end
In the implementation of delete_if
, the code can verify the value returned from yield
to decide whether or not to delete the given entry from the array. 在delete_if
的实现中,代码可以验证yield
返回的值,以决定是否从数组中删除给定的条目。
You can read Implementing Iterators in the Programming Ruby guide for more details, but it would looks something like: 您可以在Programming Ruby指南中阅读Implementing Iterators以获取更多详细信息,但它看起来像:
class Array
def delete_if
reject { |i| yield i }.to_a
end
end
The above uses yield
to pass each item in the array to the block associated with the call to delete_if
, and implicitly returns the value of the yield
to the outer reject
call. 上面使用yield
将数组中的每个项传递delete_if
调用相关联的块,并隐式返回yield
对外部reject
调用的值。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.