Created
August 28, 2011 17:07
-
-
Save aprescott/1176930 to your computer and use it in GitHub Desktop.
Simple Enumerable extension to randomly stream elements.
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
module Enumerable | |
def random_stream(&block) | |
enumerator = Enumerator.new do |y| | |
loop do | |
y << sample | |
end | |
end | |
block ? enumerator.each(&block) : enumerator | |
end | |
end | |
binary = [0, 1] | |
stream = binary.random_stream | |
stream.take(10) #=> [1, 1, 1, 1, 1, 1, 0, 1, 0, 0] | |
stream.take(10) #=> [0, 0, 1, 0, 1, 1, 0, 0, 0, 0] | |
stream.next #=> 1 | |
stream.next #=> 1 | |
stream.next #=> 0 | |
stream.peek #=> 1 | |
stream.peek #=> 1 | |
stream.peek #=> 1 | |
# ..., always the same value | |
# loops infinitely: | |
binary.random_stream do |n| | |
puts n | |
end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment