Skip to content

Instantly share code, notes, and snippets.

@danimal141
Created March 16, 2014 03:51
Show Gist options
  • Save danimal141/9578278 to your computer and use it in GitHub Desktop.
Save danimal141/9578278 to your computer and use it in GitHub Desktop.
fibonacci sequence in Ruby
# without memoizing
def fibonacci n
n < 2 ? n : fibonacci(n - 2) + fibonacci(n - 1)
end
10.times { |i| p fibonacci(i) }
# memoize
module Fibonacci
@@memo = [0, 1]
class << self
def [] n
@@memo[n] = self[n - 2] + self[n - 1] unless @@memo[n]
return @@memo[n]
end
end
end
10.times { |i| p Fibonacci[i] }
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment