Skip to content

Instantly share code, notes, and snippets.

@leemour
Last active June 7, 2018 07:31
Show Gist options
  • Save leemour/23933405a65418ee26b3571cfd077537 to your computer and use it in GitHub Desktop.
Save leemour/23933405a65418ee26b3571cfd077537 to your computer and use it in GitHub Desktop.
Even Fibonacci Numbers
module Fibonacci
class << self
def sum_of_even_upto(max)
upto(max).inject(0) do |sum, item|
item.even? ? sum + item : sum
end
end
def upto(max)
generate.take_while { |item| item <= max }
end
private
def generate
Enumerator.new do |yielder|
i = j = 1
loop do
yielder.yield i
i, j = j, i + j
end
end
end
end
end
require "minitest/autorun"
class TestFibonacci < Minitest::Test
describe '#sum_of_even_upto' do
describe 'when given positive integer' do
it 'returns a sum all even fibonacci numbers up to that integer' do
Fibonacci.sum_of_even_upto(2).must_equal 2
Fibonacci.sum_of_even_upto(4_000_000).must_equal 4_613_732
end
end
describe 'when given zero' do
it 'returns zero' do
Fibonacci.sum_of_even_upto(0).must_equal 0
end
end
describe 'when given negative integer' do
it 'returns zero' do
Fibonacci.sum_of_even_upto(-1).must_equal 0
end
end
describe 'when given a string' do
it 'raises ArgumentError' do
proc { Fibonacci.sum_of_even_upto('1') }.must_raise ArgumentError
end
end
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment