Skip to content

Instantly share code, notes, and snippets.

@aprescott
Created August 28, 2011 17:07
Show Gist options
  • Save aprescott/1176930 to your computer and use it in GitHub Desktop.
Save aprescott/1176930 to your computer and use it in GitHub Desktop.
Simple Enumerable extension to randomly stream elements.
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