Skip to content

Instantly share code, notes, and snippets.

@vderyagin
Created November 14, 2012 12:37
Show Gist options
  • Save vderyagin/4071857 to your computer and use it in GitHub Desktop.
Save vderyagin/4071857 to your computer and use it in GitHub Desktop.
cached fibonacci sequence generator in ruby
#! /usr/bin/env ruby
require 'forwardable'
require 'minitest/autorun'
class Fibonacci
extend Forwardable
def_delegator :generator, :take
def initialize
@cache = [1, 1]
end
def [](num)
take(num + 1) unless @cache[num]
@cache[num]
end
def generator
Enumerator.new do |yielder|
current_idx = 0
loop do
unless @cache[current_idx]
@cache << @cache[-1] + @cache[-2]
end
yielder << @cache[current_idx]
current_idx += 1
end
end
end
private :generator
end
if __FILE__ == $PROGRAM_NAME
describe 'fibonacci sequence generator' do
before do
@fib = Fibonacci.new
end
it 'returns first item right' do
@fib[0].must_equal 1
end
it 'returns second item right' do
@fib[1].must_equal 1
end
it 'returns third item right' do
@fib[2].must_equal 2
end
it 'returns fourth item right' do
@fib[3].must_equal 3
end
it 'returns list right' do
@fib.take(10).must_equal [1, 1, 2, 3, 5, 8, 13, 21, 34, 55]
end
end
end
# >> Run options: --seed 14468
# >>
# >> # Running tests:
# >>
# >> .....
# >>
# >> Finished tests in 0.000463s, 10804.3399 tests/s, 10804.3399 assertions/s.
# >>
# >> 5 tests, 5 assertions, 0 failures, 0 errors, 0 skips
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment