Ruby hash equivalent to Python dict setdefault

后端 未结 5 1963
悲&欢浪女
悲&欢浪女 2021-01-17 12:30

In Python it is possible to read a dictionary/hash key while at the same time setting the key to a default value if one does not already exist.

For example:

5条回答
  •  渐次进展
    2021-01-17 13:03

    You can simply pass a block to the Hash constructor:

    hash = Hash.new do |hash, key|
      hash[key] = :default
    end
    

    The block will be invoked when an attempt to access a non-existent key is made. It will be passed the hash object and the key. You can do anything you want with them; set the key to a default value, derive a new value from the key, etc.

    If you already have a Hash object, you can use the default_proc= method:

    hash = { key: 'value' }
    
    # ...
    
    hash.default_proc = proc do |hash, key|
      hash[key] = :default
    end
    

提交回复
热议问题