ruby – Enumerator#feed的魔力

有这个 Enumerator#feed method,我偶然发现了.它被定义为:

feed obj → nil
Sets the value to be returned by the next yield inside e. If the value is not set,the yield returns nil. This value
is cleared after being yielded.

我研究了例子,并认为»Yay!«,这应该使用feed:

enum = ['cat','bird','goat'].each # creates an enumerator
enum.next #=> 'cat'
enum.feed 'dog'
enum.next #=> returns 'bird',but I expected 'dog'

但它不行.我假设,它不返回’狗’,因为每个都不在内部使用收益.

事实是,我无法从文档中的给定示例中推断任何真实世界的用例,Google不是这个问题的朋友,(从我所尝试的)feed似乎不能很好地与其他枚举/枚举方法.

请问,请给我一个很好的例子,说明饲料,所以我可以让我的头脑吗?

解决方法

def meth
 [1,2,3].each {|e| p yield(e)}
end

m = to_enum(:meth)
m.next #=> 1

m.feed "e"

m.next
#printed: "e"
#return => 2

正如你所看到的,feed会影响yield的结果,但是会影响枚举器的结果
方法需要注意

现在看你自己的例子:

a = ['cat','goat']
m = a.to_enum(:map!)
m.next
m.feed("dog")
m.next
m.next
p a #=> ["dog",nil,"goat"]

饲料工作方式:

first you need to call next then you call feed to set the value,and then the next call of next does apply the change (even if it raise an StopIteration error.)

有关更多的解释,请看这里的线程:Enum#feed:.这有关于枚举#feed的正确解释.

相关文章

validates:conclusion,:presence=>true,:inclusion=>{...
一、redis集群搭建redis3.0以前,提供了Sentinel工具来监控各...
分享一下我老师大神的人工智能教程。零基础!通俗易懂!风趣...
上一篇博文 ruby传参之引用类型 里边定义了一个方法名 mo...
一编程与编程语言 什么是编程语言? 能够被计算机所识别的表...
Ruby类和对象Ruby是一种完美的面向对象编程语言。面向对象编...