Created
September 28, 2024 09:54
-
-
Save havenwood/5ae8750820a743da027a9969ef1bb988 to your computer and use it in GitHub Desktop.
Enumerator#feed examples
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
class Integer | |
def stream(by: 1) | |
Enumerator.new Float::INFINITY do |yielder| | |
int = self | |
loop do | |
fed = yielder.yield(int) | |
int += fed if fed | |
int += by | |
end | |
end | |
end | |
end | |
flow = 42.stream | |
flow.next #=> 42 | |
flow.next #=> 43 | |
flow.feed 100 #=> nil | |
flow.next #=> 144 | |
flow.rewind | |
flow.next #=> 42 | |
class Enumerator | |
def self.repeatedly(&block) | |
raise ArgumentError, 'Block required' unless block_given? | |
Enumerator.new Float::INFINITY do |yielder| | |
loop do | |
fed = yielder.yield block.call | |
block = fed if fed | |
end | |
end | |
end | |
end | |
enum = Enumerator.repeatedly { 42 } | |
enum.next #=> 42 | |
enum.first 4 #=> [42, 42, 42, 42] | |
enum.feed ->{ rand 42 } | |
enum.next #=> 11 # now random | |
enum.first 4 #=> [32, 4, 1, 28] |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment