Created
March 10, 2012 15:40
-
-
Save al-the-x/2011813 to your computer and use it in GitHub Desktop.
Orlando Ruby Coding Dojo - 3/8/2011
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
require "enumerator" | |
class Solution | |
include Enumerable | |
def initialize ( cap=nil ) | |
@e = Enumerator.new do |yielder| | |
a = b = 1 | |
loop do | |
break if cap && b > cap | |
yielder << b | |
a, b = b, a + b | |
end | |
end | |
end | |
def each | |
yield @e.next | |
end | |
end #Solution |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#!/usr/bin/env ruby1.9 | |
require "test/unit" | |
require_relative "main" | |
# Each new term in the Fibonacci sequence is generated by adding the previous two terms. By starting with 1 and 2, the | |
# first 10 terms will be: | |
# | |
# 1, 2, 3, 5, 8, 13, 21, 34, 55, 89, ... | |
# | |
# By considering the terms in the Fibonacci sequence whose values do not exceed four million, find the sum of the | |
# even-valued terms. | |
class SolutionTest < Test::Unit::TestCase | |
def test_fib | |
solution = Solution.new | |
expected = [ 1, 2, 3, 5, 8, 13, 21, 34, 55, 89 ] | |
expected.each do |n| | |
assert_equal n, solution.each | |
end | |
end | |
def test_fib_with_cap | |
solution = Solution.new 10 | |
expected = [ 1, 2, 3, 5, 8 ] | |
expected.each do |n| | |
assert_equal n, solution.each | |
end | |
assert_raise StopIteration do | |
solution.each | |
end | |
end | |
def test_solution | |
actual = Solution.new(10).select do |n| | |
n.even? | |
end | |
assert_equal [2, 8 ], actual | |
assert_equal 0, Solution.new(4000000).select{|n| n.even? }.reduce(:+) | |
end | |
end #SolutionTest |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment