Ruby hash equivalent to Python dict setdefault

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

    If you only want to modify the value returned by setdefault, you can express this via Hash#merge!:

    Python:

    >>> d = {}
    >>> d.setdefault("k", []).append("v")
    >>> d
    {'k': ['v']}
    

    Ruby:

    [28] pry(main)> h = {}
    => {}
    [29] pry(main)> h.merge!(k: [:v]) { |_key, old, new| old.concat(new) }
    => {:k=>[:v]}
    [30] pry(main)> h
    => {:k=>[:v]}
    

提交回复
热议问题