Skip to content

Instantly share code, notes, and snippets.

@orend
Created September 11, 2012 13:34
Show Gist options
  • Select an option

  • Save orend/3698516 to your computer and use it in GitHub Desktop.

Select an option

Save orend/3698516 to your computer and use it in GitHub Desktop.
memoization using a hash. from rubies in the rough
def fibonacci(nth, series = method(:fibonacci))
if nth < 2
nth
else
series[nth - 2] + series[nth - 1]
end
end
# The easiest memoization in the world:
fibs = Hash.new { |series, nth| series[nth] = fibonacci(nth, series) }
p fibs[100]
# put diffrently:
 fibonacci = Hash.new { |numbers, index|
numbers[index] = fibonacci[index - 2] + fibonacci[index - 1]
}.update(0 => 0, 1 => 1)
p fibonacci[300]
# 222232244629420445529739893461909967206666939096499764990979600
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment