main
1#Each new term in the Fibonacci sequence is generated by adding the previous two terms.
2#By starting with 1 and 2, the first 10 terms will be:
3
4#1, 2, 3, 5, 8, 13, 21, 34, 55, 89, ...
5
6#By considering the terms in the Fibonacci sequence whose values do not exceed
7#four million, find the sum of the even-valued terms.
8describe "problem two" do
9 def fib
10 Enumerator.new do |yielder|
11 x, y = 1, 2
12 loop do
13 yielder.yield x
14 tmp = x
15 x = y
16 y = tmp + y
17 end
18 end
19 end
20
21 def sum_of_first(n)
22 fib.take(n).inject(0) do |memo, x|
23 memo + x
24 end
25 end
26
27 it "computes the sum" do
28 result = sum_of_first(10)
29 expect(result).to eql([1, 2, 3, 5, 8, 13, 21, 34, 55, 89].inject(0) {|memo, x| memo + x })
30 end
31
32 it "accumulates" do
33 items = fib.take_while { |n| n < 4_000_000 }.find_all(&:even?)
34 result = items.inject(0) { |memo, x| memo + x }
35 expect(result).to eql(4613732)
36 end
37
38 it "can accumulates manually" do
39 total = 0
40 enumerator = fib
41 current = enumerator.next
42 loop do
43 break if current >= 4_000_000
44
45 total += current if current.even?
46 current = enumerator.next
47 end
48 expect(total).to eql(4613732)
49 end
50end