Skip to content

Instantly share code, notes, and snippets.

@supersimple
Created January 14, 2018 01:54
Show Gist options
  • Save supersimple/bb7b9ecb47ae372b243693cd5b429f01 to your computer and use it in GitHub Desktop.
Save supersimple/bb7b9ecb47ae372b243693cd5b429f01 to your computer and use it in GitHub Desktop.
Some ways to handle a fibonacci sequence in Ruby
# 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