Setting ruby hash .default to a list [duplicate]

This is a very useful idiom:

(myhash[key] ||= []) << value

It can even be nested:

((myhash[key1] ||= {})[key2] ||= []) << value

The other way is to do:

myhash = Hash.new {|hash,key| hash[key] = []}

But this has the significant side-effect that asking about a key will create it, which renders has_key? fairly useless, so I avoid this method.

Leave a Comment

Hata!: SQLSTATE[HY000] [1045] Access denied for user 'divattrend_liink'@'localhost' (using password: YES)