Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

The magic of Enumerator#feed

Tags:

ruby

There is this Enumerator#feed method, I discovered by accident. It is defined as:

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.

I studied the examples and thought »Yay!«, this should work using feed:

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

But it does not work. I assume, it does not return 'dog', because each is not using yield internally.

The thing is, that I couldn't deduce any real world use cases from the given example in the documentation, Google is not a friend with this question, and (from what I've tried) feed seems not to work well with the other Enumerator/Enumeration methods.

Can you, please, give me a good example which explains feed, so I can get my head around it?

like image 213
tessi Avatar asked May 22 '13 13:05

tessi


1 Answers

As an addendum, from the 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
like image 112
ian Avatar answered Sep 21 '22 06:09

ian