2013-05-22 42 views
14

有這個Enumerator#feed method,我偶然發現。它被定義爲:Enumerator#feed的神奇

飼料OBJ→零
設置於由內部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,所以我可以把它放在頭上嗎?

回答

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作品:

第一下一步要打電話,那麼你需要調用feed設置的值,然後接下來的下一個電話不適用的變化(即使它引發StopIteration error

詳細解釋一下在這裏的線程:Enum#feed:。這有關於enum#feed的正確解釋。

+1

請在後一些背景。 StackOverflow上的答案不應該是「[僅僅是一個鏈接到外部網站](http://stackoverflow.com/faq#deletion)」 – Gareth

+0

@Gareth可以嗎?或更多的上下文我需要添加?我認爲我在那裏寫的是關於'enum#feed'的。 –

+0

@Priti,我真的很喜歡'map!'的例子 - 謝謝。仍然希望通過更多的例子獲得更多的答案。目前,「feed」在「真實世界」中似乎很沒用。 – tessi

0

作爲附錄,從current docs for 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