3 ms·
I'm actually still confused as to the right way to do defaultdict in Ruby. StackOverflow has three ways... http://stackoverflow.com/questions/190740/setting-r
by pbh 15y ago
I'm actually still confused as to the right way to do defaultdict in Ruby.
StackOverflow has three ways...
http://stackoverflow.com/questions/190740/setting-ruby-hash-default-to-a-list http://stackoverflow.com/questions/190740/setting-ruby-hash-...
(i) The most idiomatic way seems to be:
(myhash[key] ||= []) << value
(ii) You can use .default
myhash.default = []
(iii) You can use a default proc, as you note:
myhash = Hash.new {|h,k| h[k] = []}
The problem with (i) is that it has weird results if myhash[key] has an actual value, but that value is falsy (e.g., nil or false).
The problem with (ii) is that all default values share the same empty array, so when that gets changed, they all get changed.
The one weird behavior with (iii), at least to me, is that if you access (but don't modify) myhash[k], then it creates a new key with the default value.