有一个Enumerator#feed法,我偶然发现的。它的定义是:
feed→nil 设置e内下一个收益率返回的值。如果未设置该值,则返回零。此值在生成后被清除。
我研究了这些例子和想法!耶,这应该可以使用feed。
enum = ['cat', 'bird', 'goat'].each # creates an enumerator
enum.next #=> 'cat'
enum.feed 'dog'
enum.next #=> returns 'bird', but I expected 'dog'但不起作用。我想,它不会返回'dog',因为each内部没有使用yield。
问题是,我无法从文档中的给定示例中推断出任何真实的用例,Google不是这个问题的朋友,而且(根据我的尝试) feed似乎不能很好地与其他Enumerator/Enumeration方法一起工作。
你能给我举个很好的例子来解释feed,这样我才能把我的头挪开吗?
发布于 2013-05-22 13:49:29
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如您所见,提要会影响产量的结果,但是枚举器方法需要注意它--。
现在看看您自己的例子:
a = ['cat', 'bird', 'goat']
m = a.to_enum(:map!)
m.next
m.feed("dog")
m.next
m.next
p a #=> ["dog", nil, "goat"]feed的工作方式:
首先需要调用next,然后调用feed来设置值,然后next的下一个调用将应用更改(即使它会引发
StopIteration error)。
要获得更多的解释,请看这里的线程:Enum#feed:。这对enum#feed有正确的解释。
发布于 2018-02-25 16:51:37
作为增编,来自Ruby v2.5的当前文档
# Array#map passes the array's elements to "yield" and collects the
# results of "yield" as an array.
# Following example shows that "next" returns the passed elements and
# values passed to "feed" are collected as an array which can be
# obtained by StopIteration#result.
e = [1,2,3].map
p e.next #=> 1
e.feed "a"
p e.next #=> 2
e.feed "b"
p e.next #=> 3
e.feed "c"
begin
e.next
rescue StopIteration
p $!.result #=> ["a", "b", "c"]
endhttps://stackoverflow.com/questions/16692788
复制相似问题