Ruby hash equivalent to Python dict setdefault

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

    Not to beat a dead horse here, but setDefault acts more like fetch does on a hash. It does not act the same way default does on a hash. Once you set default on a hash, any missing key will use that default value. That is not the case with setDefault. It stores the value for only the one missing key and only if it fails to find that key. That whole stores the new key value pair piece is where it differs from fetch.

    At the same time, we currently just do what setDefault does like this:

    h = {}
    h['key'] ||= 'value'
    

    Ruby continued to drive point home:

    h.default = "Hey now"
    h.fetch('key', 'default')                       # => 'value'
    h.fetch('key-doesnt-exist', 'default')          # => 'default'
    # h => {'key' => 'value'}
    h['not your key']                               # => 'Hey now'
    

    Python:

    h = {'key':'value'}
    h.setdefault('key','default')                   # => 'value'
    h.setdefault('key-doesnt-exist','default')      # => 'default'
    # h {'key': 'value', 'key-doesnt-exist': 'default'}
    h['not your key']                               # => KeyError: 'not your key'
    

提交回复
热议问题