Skip to content

Instantly share code, notes, and snippets.

@simonwo
Last active August 29, 2015 14:03
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 simonwo/80681d415138aad67572 to your computer and use it in GitHub Desktop.
Save simonwo/80681d415138aad67572 to your computer and use it in GitHub Desktop.
Cached Fibonacci in Ruby
Fibonacci = Hash.new {|h, i| h[i] = h[i-1] + h[i-2]}
Fibonacci[1] = 1
Fibonacci[2] = 1
# And now it's ready to use!
puts Fibonacci[6] # => 8
p Fibonacci # => {1=>1, 2=>1, 3=>2, 4=>3, 5=>5, 6=>8}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment