Is it possible to do something like this:

hash[:key] = something
hash[:key] #=> 1
hash[:key] #=> 2
hash[:key] #=> 3
 
 
where I store something in a hash that automatically increments each time it is accessed
Apparently it is if you subclass Hash and store lambdas:
class CallHash < Hash
def [](key)
if fetch(key).respond_to?(:call)
fetch(key).call
else
fetch(key)
end
rescue KeyError
nil
end
end
class CallHash < Hash
def [](key)
value = fetch key, nil
return value.call if value.respond_to?(:call)
value
end
end
You already invited:

Walter

Upvotes from:

Also:
2.5.3 :001 > i = 0
=> 0
2.5.3 :002 > hash = Hash.new { i += 1 }
=> {}
2.5.3 :003 > hash[:a]
=> 1
2.5.3 :004 > hash[:a]
=> 2
2.5.3 :005 > hash[:a]
=> 3
2.5.3 :006 > hash[:a]
=> 4

Amos

Upvotes from:

It works due to the escaping of the closure scope by i, and the fact that you can give hash a block that returns a default value for a key.

If you wanna answer this question please Login or Register