Ruby hash equivalent to Python dict setdefault

后端 未结 5 1909
悲&欢浪女
悲&欢浪女 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

    There is no equivalent to this function in Python. You can always use monkey patching to get this functionality:

    class Hash
    
      def setdefault(key, value)
        if self[key].nil?
          self[key] = value
        else
          self[key]
        end
      end
    
    end
    
    h = Hash.new
    h = { 'key' => 'value' }
    h.setdefault('key', 'default')
    # => 'value'
    h.setdefault('key-doesnt-exist', 'default')
    # => 'default'
    

    But keep in mind that monkey patching is often seen as a taboo, at least in certain code environments.

    The golden rule of monkey patching applies: just because you could, doesn’t mean you should.

    The more idiomatic way is to define default values through the Hash constructor by passing an additional block or value.

提交回复
热议问题