Skip to content

Instantly share code, notes, and snippets.

@nicksieger
Created January 12, 2012 18:08
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save nicksieger/1602130 to your computer and use it in GitHub Desktop.
Save nicksieger/1602130 to your computer and use it in GitHub Desktop.
require 'enumerator'
class FibonacciSeq
include Enumerable
def initialize
@prev = 0
@curr = 1
end
def each(&block)
if block_given?
loop do
@prev, @curr = @curr, @prev + @curr
block.call(@prev)
end
else
Enumerator.new(self)
end
end
end
p FibonacciSeq.new.first
p FibonacciSeq.new.first(10)
enum = FibonacciSeq.new.each
1.upto(10) do |i|
p enum.next
end
$ rvm 1.8.7,1.9.2,jruby,jruby-head do ruby -v r.rb
ruby 1.8.7 (2011-06-30 patchlevel 352) [i686-darwin11.0.1]
1
[1, 1, 2, 3, 5, 8, 13, 21, 34, 55]
/Users/nicksieger/.rvm/rubies/ruby-1.8.7-p352/lib/ruby/1.8/generator.rb:188: warning: method redefined; discarding old next
/Users/nicksieger/.rvm/rubies/ruby-1.8.7-p352/lib/ruby/1.8/generator.rb:200: warning: method redefined; discarding old rewind
1
1
2
3
5
8
13
21
34
55
ruby 1.9.2p290 (2011-07-09 revision 32553) [x86_64-darwin11.0.1]
1
[1, 1, 2, 3, 5, 8, 13, 21, 34, 55]
1
1
2
3
5
8
13
21
34
55
jruby 1.6.5 (ruby-1.8.7-p330) (2011-10-25 9dcd388) (Java HotSpot(TM) Client VM 1.6.0_29) [darwin-i386-java]
1
[1, 1, 2, 3, 5, 8, 13, 21, 34, 55]
1
1
2
3
5
8
13
21
34
55
jruby 1.7.0.dev (ruby-1.8.7-p357) (2012-01-12 0e83d96) (Java HotSpot(TM) Client VM 1.6.0_29) [darwin-i386-java]
[1]
[[1], [1], [2], [3], [5], [8], [13], [21], [34], [55]]
1
1
2
3
5
8
13
21
34
55
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment