Created
January 14, 2018 01:54
-
-
Save supersimple/bb7b9ecb47ae372b243693cd5b429f01 to your computer and use it in GitHub Desktop.
Some ways to handle a fibonacci sequence in Ruby
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
# This prints out the nth member of the sequence | |
def fib(n) | |
last_two = [0,1] | |
3.upto(n) do | |
last_two = last_two[1], last_two.inject(:+) | |
end | |
puts last_two.last | |
end | |
# This prints out the first 20 members | |
(1..20).inject( [0, 1] ) { | fib | fib << fib.last(2).inject(:+) } |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment