Last active
August 29, 2015 14:10
-
-
Save avdi/20037a488409dd2d7df1 to your computer and use it in GitHub Desktop.
This file contains hidden or 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
module Enumerable | |
def each_with_emptiness | |
return to_enum(__callee__) unless block_given? | |
if empty? | |
yield nil, true | |
else | |
each do |element| | |
yield element, false | |
end | |
end | |
end | |
end | |
[].each_with_emptiness do |n, empty| | |
break puts "None found" if empty | |
puts "Number: #{n}" | |
end | |
# >> None found |
@ReneB I think the use of peek
and StopIteration
is a nice update as Enumerator does not require a #empty?
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
I like it, but I have a couple of questions (which may go beyond the original intention of the gist, in which case, sorry to bother you).
First off, I think this also begs for a
.with_emptiness
method onEnumerator
, since alleach_with_x
methods I know of (which is, admittedly, only 2:each_with_object
andeach_with_index
) are also available alseach.with_x
And would it, then, help to implement this as something like this, or am I missing some subtleties (aside from the fact that this kind of methods on
Enumerator
is usually implemented in C)?