Welcome toVigges Developer Community-Open, Learning,Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
409 views
in Technique[技术] by (71.8m points)

hashmap - Setting ruby hash .default to a list


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to Vigges Developer Community for programmer and developer-Open, Learning and Share
...