4 ms·
I didn't know you could do this in ruby: Hash.new {|h,k| h[k] = []} That makes counters easier, as in: x = Hash.new {|k,v| k[v] = 0} x['foo'] +=
by chrismealy 15y ago
I didn't know you could do this in ruby:
Hash.new {|h,k| h[k] = []}
That makes counters easier, as in:
x = Hash.new {|k,v| k[v] = 0}
x['foo'] += 1
Or simply:
x = Hash.new 0
- pbh 15y agoI'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.