Skip to content

Instantly share code, notes, and snippets.

@mrryanjohnston
Last active June 7, 2018 00:05
Show Gist options
  • Save mrryanjohnston/7357f8f88cd214ed294a97610c5b01a5 to your computer and use it in GitHub Desktop.
Save mrryanjohnston/7357f8f88cd214ed294a97610c5b01a5 to your computer and use it in GitHub Desktop.
Even Fibonacci Numbers

Fibonacci

Description

A convenience library for calculating fibonacci numbers.

Usage

Fibonacci.new.tap do |fib|
  # To get all the numbers
  fib.to_a  

  # To get the even numbers
  fib.evens

  # To get the odd numbers
  fib.odds

  # To get a string representation of the sequence
  fib.to_s
end

# The default limit is 4,000,000. To use a different limit:
Fibonacci.new(100)

Testing

$ rspec fibonacci_spec.rb
class Fibonacci
include Enumerable
attr_accessor :limit
def initialize(limit=4_000_000)
@limit = limit
end
def each
previous = 0
current = 1
while current <= limit
yield current
old_previous = previous
previous = current
current += old_previous
end
end
def evens
select { |f| f % 2 == 0 }
end
def odds
select { |f| f % 2 != 0 }
end
def to_s
select { |f| f }.to_s
end
end
require 'rspec'
require_relative 'fibonacci'
RSpec.describe Fibonacci do
context 'with default initialization' do
let(:fib) { described_class.new }
it 'is enumerable' do
expect(fib).to respond_to :each
end
it 'up to a default limit of 4,000,000' do
expect(fib.to_a.last).to be < 4_000_000
end
it 'can calculate even numbers' do
expect(fib.evens.to_a).to eq [2, 8, 34, 144, 610, 2584, 10946, 46368, 196418, 832040, 3524578]
end
it 'can calculate odd numbers' do
expect(fib.odds.to_a).to eq [1, 1, 3, 5, 13, 21, 55, 89, 233, 377, 987, 1597, 4181, 6765, 17711, 28657, 75025, 121393, 317811, 514229, 1346269, 2178309]
end
it 'has nice stringified version' do
expect(fib.to_s).to eq "[1, 1, 2, 3, 5, 8, 13, 21, 34, 55, 89, 144, 233, 377, 610, 987, 1597, 2584, 4181, 6765, 10946, 17711, 28657, 46368, 75025, 121393, 196418, 317811, 514229, 832040, 1346269, 2178309, 3524578]"
end
end
context 'with custom limit' do
let(:fib) { described_class.new(100) }
it 'is enumerable' do
expect(fib).to respond_to :each
end
it 'stops calculating number up to its limit' do
expect(fib.to_a.last).to eq 89
end
it 'can calculate even numbers' do
expect(fib.evens.to_a).to eq [2, 8, 34]
end
it 'can calculate odd numbers' do
expect(fib.odds.to_a).to eq [1, 1, 3, 5, 13, 21, 55, 89]
end
it 'has nice stringified version' do
expect(fib.to_s).to eq "[1, 1, 2, 3, 5, 8, 13, 21, 34, 55, 89]"
end
end
end
source 'https://rubygems.org'
gem 'rspec'
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment