Class: Fibber

Inherits:
Object
  • Object
show all
Defined in:
src/ruby/bin/math_server.rb

Overview

Holds state for a fibonacci series

Instance Method Summary collapse

Constructor Details

#initialize(limit) ⇒ Fibber


65
66
67
68
# File 'src/ruby/bin/math_server.rb', line 65

def initialize(limit)
  fail "bad limit: got #{limit}, want limit > 0" if limit < 1
  @limit = limit
end

Instance Method Details

#generatorObject


70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
# File 'src/ruby/bin/math_server.rb', line 70

def generator
  return enum_for(:generator) unless block_given?
  idx, current, previous = 0, 1, 1
  until idx == @limit
    if idx.zero? || idx == 1
      yield Math::Num.new(num: 1)
      idx += 1
      next
    end
    tmp = current
    current = previous + current
    previous = tmp
    yield Math::Num.new(num: current)
    idx += 1
  end
end