13

有这个Enumerator#feed 方法,我偶然发现的。它被定义为:

feed obj → nil
设置 e 中下一个 yield 返回的值。如果未设置该值,则产量返回 nil。该值在产生后被清除。

我研究了这些示例并认为»耶!«,这应该使用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内部使用。

问题是,我无法从文档中的给定示例中推断出任何真实世界的用例,谷歌不是这个问题的朋友,而且(从我尝试过的)feed似乎与其他Enumerator/Enumeration方法。

请你给我一个很好的例子来解释feed,所以我可以理解它吗?

4

2 回答 2

6
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

于 2013-05-22T13:49:29.883 回答
1

作为附录,来自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"]
end
于 2018-02-25T16:51:37.857 回答