Advertisement
saasbook

fib_solution.rb

Jan 10th, 2012
245
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Ruby 0.57 KB | None | 0 0
  1. # Each instance of FibSequence remembers how many Fibonacci numbers are
  2. #   desired using the @limit instance variable.
  3. # FibSequence#each is just  an instance method that yields the
  4. #   first @limit Fibonacci numbers one at a time.
  5. class FibSequence
  6.   include Enumerable
  7.   def initialize(limit) ; @limit = limit ; end
  8.   def each
  9.     case @limit
  10.     when 0 then return
  11.     when 1 then yield 1
  12.     else
  13.       yield 1
  14.       yield 1
  15.       lastfib,nextfib = 1,2
  16.       @limit.downto(3) do
  17.         yield nextfib
  18.         lastfib, nextfib = nextfib, nextfib+lastfib
  19.       end
  20.     end
  21.   end
  22. end
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement