微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

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的正确解释.

原文地址:https://www.jb51.cc/ruby/271430.html

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。

相关推荐