Skip to content

Instantly share code, notes, and snippets.

@johana-star
Created April 11, 2016 01:21
Show Gist options
  • Save johana-star/bc4e78ec1c945f9fd6375546c9e75e71 to your computer and use it in GitHub Desktop.
Save johana-star/bc4e78ec1c945f9fd6375546c9e75e71 to your computer and use it in GitHub Desktop.
require 'rspec'
class Fibonacci
def self.memoize(method_name)
slow_method_name = "slow_#{method_name}".to_sym
alias_method slow_method_name, method_name
cache ||= {}
define_method method_name do |index|
unless cache.key?(index)
cache[index] = send(slow_method_name, index)
end
cache[index]
end
end
def at_index(index)
return index if index <= 1
at_index(index - 2) + at_index(index - 1)
end
memoize :at_index
end
describe 'Fibonacci#at_index' do
SEQUENCE = {
0 => 0,
1 => 1,
2 => 1,
3 => 2,
4 => 3,
5 => 5,
6 => 8,
35 => 9227465
}
SEQUENCE.each do |index, expected_result|
it "receives #{index} and returns #{expected_result}" do
expect(Fibonacci.new.at_index(index)).to eq expected_result
end
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment