Created
January 12, 2012 18:08
-
-
Save nicksieger/1602130 to your computer and use it in GitHub Desktop.
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
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 |
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
$ 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