Created
May 25, 2014 10:21
-
-
Save appsol/e410ca10c6f1890de60d to your computer and use it in GitHub Desktop.
Saasbook Project 3.7
This file contains 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 ruby | |
# Project 3.7 | |
class FibSequence | |
include Enumerable | |
def initialize(n) | |
@max = n | |
@x = 0 | |
@y = 1 | |
end | |
def each | |
i = 1 | |
until i > @max do | |
yield @y | |
@z = @y | |
@y = @x + @y | |
@x = @z | |
i+= 1 | |
end | |
end | |
end | |
# Fibonacci iterator should be callable like this: | |
f = FibSequence.new(6) # just the first 6 Fibonacci numbers | |
f.each { |s| print(s,':') } # => 1:1:2:3:5:8: | |
f.reject { |s| s.odd? } # => [2, 8] | |
f.reject(&:odd?) # => [2, 8] (a shortcut!) | |
f.map { |x| 2*x } # => [2, 2, 4, 6, 10, 16] |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment