Hashes of Hashes Idiom in Ruby?

后端 未结 3 859
旧巷少年郎
旧巷少年郎 2020-12-12 20:58

Creating hashes of hashes in Ruby allows for convenient two (or more) dimensional lookups. However, when inserting one must always check if the first index already exists i

3条回答
  •  攒了一身酷
    2020-12-12 21:21

    Autovivification, as it's called, is both a blessing and a curse. The trouble can be that if you "look" at a value before it's defined, you're stuck with this empty hash in the slot and you would need to prune it off later.

    If you don't mind a bit of anarchy, you can always just jam in or-equals style declarations which will allow you to construct the expected structure as you query it:

    ((h ||= { })['w'] ||= { })['z']
    

提交回复
热议问题