Hashes of Hashes Idiom in Ruby?

后端 未结 3 870
旧巷少年郎
旧巷少年郎 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:38

    You can pass the Hash.new function a block that is executed to yield a default value in case the queried value doesn't exist yet:

    h = Hash.new { |h, k| h[k] = Hash.new }
    

    Of course, this can be done recursively. There's an article explaining the details.

    For the sake of completeness, here's the solution from the article for arbitrary depth hashes:

    hash = Hash.new(&(p = lambda{|h, k| h[k] = Hash.new(&p)}))
    

    The person to originally come up with this solution is Kent Sibilev.

提交回复
热议问题