Skip to content

Instantly share code, notes, and snippets.

@mark
Last active November 22, 2016 19:10
Show Gist options
  • Select an option

  • Save mark/0bf209dc1bf5584b1b4fcc32cdc612f8 to your computer and use it in GitHub Desktop.

Select an option

Save mark/0bf209dc1bf5584b1b4fcc32cdc612f8 to your computer and use it in GitHub Desktop.

Revisions

  1. mark revised this gist Nov 22, 2016. 1 changed file with 10 additions and 5 deletions.
    15 changes: 10 additions & 5 deletions fiber-enumerable.rb
    Original file line number Diff line number Diff line change
    @@ -6,11 +6,16 @@ class MyWrapper

    def initialize
    @fiber = fiber
    @results = []
    end

    def each
    @results.each { |obj| yield obj }

    while @fiber.alive?
    yield @fiber.resume
    obj = @fiber.resume
    @results << obj
    yield obj
    end
    end

    @@ -38,12 +43,12 @@ def fiber
    pp e.take(5)
    # CREATING 3
    # CREATING 4
    #=> [0, 1, 2, 3, 4]

    pp e.take(10)
    # CREATING 5
    # CREATING 6
    # CREATING 7
    #=> [3, 4, 5, 6, 7]

    pp e.take(10)
    # CREATING 8
    # CREATING 9
    #=> [8, 9, 10]
    #=> [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
  2. mark created this gist Nov 22, 2016.
    49 changes: 49 additions & 0 deletions fiber-enumerable.rb
    Original file line number Diff line number Diff line change
    @@ -0,0 +1,49 @@
    require 'fiber'
    require 'pp'

    class MyWrapper
    include Enumerable

    def initialize
    @fiber = fiber
    end

    def each
    while @fiber.alive?
    yield @fiber.resume
    end
    end

    private

    def fiber
    Fiber.new do
    10.times do |i|
    puts "CREATING #{i}"
    Fiber.yield(i)
    end
    end
    end

    end

    e = MyWrapper.new

    pp e.take(3)
    # CREATING 0
    # CREATING 1
    # CREATING 2
    #=> [0, 1, 2]

    pp e.take(5)
    # CREATING 3
    # CREATING 4
    # CREATING 5
    # CREATING 6
    # CREATING 7
    #=> [3, 4, 5, 6, 7]

    pp e.take(10)
    # CREATING 8
    # CREATING 9
    #=> [8, 9, 10]