Created
January 11, 2016 16:13
-
-
Save anonymous/b8eec52d81be94eac7e0 to your computer and use it in GitHub Desktop.
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
# in the right spirit of lazy evaluation & enumeration | |
module Enumerable | |
def enum_block() | |
Enumerator.new() { |y| each { |val| yield(val, y) } } | |
end | |
def lazy_select() | |
Enumerator.new() { |y| each { |val| y << val if yield(val) } } | |
end | |
end | |
# usage | |
def test_enum_block() | |
a = (1..10).to_a | |
la = a.lazy_select { |v| v.even? } | |
# -------------------------------- | |
ba = a.enum_block { |v, y| y << v if v.odd? } | |
# this one seems too trivial because of the trivial test | |
# the right usage could be with havier resources with deeper nesting like calling from block | |
# e.g. | |
# files.enum_block { |fn, yld| TagLib::FileRef.open(fn) { |fr| yld << fr if fr && fr.tag } }.each { |fr| puts fr.tag.track } | |
end | |
test_enum_block() | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment