4 ms·
> There are examples of the opposite too, though. Ruby's Hash does not insert the entry: It does if you initialise the hash with a block to do so: m = Has
by masklinn 4y ago
> There are examples of the opposite too, though. Ruby's Hash does not insert the entry:
It does if you initialise the hash with a block to do so:
m = Hash.new {|h, k| h[k] = 0}
m["nonexistent"]
m.length # => 1
That is, essentially, what defaultdict does. Just through subclassing (because `dict` does not provide such a fallback, but it has a magic method you can override to customise the mapping's behaviour in that case).