Skip to content

Instantly share code, notes, and snippets.

@sgonyea
Created July 18, 2012 03:28
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save sgonyea/3133987 to your computer and use it in GitHub Desktop.
Save sgonyea/3133987 to your computer and use it in GitHub Desktop.
Infinite Cache: Python vs. Ruby
# In Python:
from collections import defaultdict
def infinite_cache():
cache = lambda: defaultdict(cache)
return cache()
cache = infinite_cache()
# In Ruby:
cache = Hash.new do |h,k|
h[k] = Hash.new(&h.default_proc)
end
# Or, if you want to mimic the Python version:
def infinite_cache
block = lambda {|h,k| h[k] = Hash.new(&block) }
Hash.new(&block)
end
cache = infinite_cache
# Mimic it even further, as Ruby's Hash doesn't have quite the same behavior as Python's "defaultdict" wrapper:
class DefaultHash < Hash
def initialize(value=nil, &block)
value ||= block
case value
when Proc, Method then self.default_proc = proc {|h,k| h[k] = value.call }
when Class then self.default_proc = proc {|h,k| h[k] = value.new }
else
self.default = value
end
end
end
def infinite_cache
cache = proc{ DefaultHash.new(cache) }
cache[]
end
cache = infinite_cache
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment