Created
January 9, 2015 20:32
-
-
Save avdi/d9d92640e570fcba2988 to your computer and use it in GitHub Desktop.
Behold, the null enumerator.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
e = loop | |
e # => #<Enumerator: main:loop> | |
e.next # => nil | |
e.next # => nil | |
e.peek # => nil | |
e.size # => Infinity | |
e.rewind | |
e.next # => nil |
Interestingly, @Peeja, at least next_values
agrees with you:
e.next_values # => []
[5].cycle
Nice.
@AaronLasseigne Ooh, very nice.
@avdi That's interesting. It's a shame #with_object
doesn't use use #next_values
. I wonder if Ruby would accept a patch for it…
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
It's certainly useful to have an infinite, constant enumerator, but I think the cases where you want it to be constantly
nil
are going to be rare.Incidentally, what's the easiest way to make a constant enumerator, one that always returns, say 5? Off the top of my head, the best I've got is:
but that seems like way too much code for something so fundamental.
Actually, @avdi,
loop
breaks the consistency a bit because it doesn't yield anything to its block (that is, its block takes arity 0), and so its enumerator should return 0 things each time it's called. But since that doesn't quite make sense, it returnsnil
.But if it did somehow return 0 things, this would be a much nicer way to create a constant enumerator:
Unfortunately,
loop.with_object(5).first == [nil, 5]
.