Ruby散列相当于Python dict setdefault [英] Ruby hash equivalent to Python dict setdefault

查看:111
本文介绍了Ruby散列相当于Python dict setdefault的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在Python中,可以读取字典/散列键,同时将键设置为默认值(如果尚不存在)。

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.

例如:

>>> d={'key': 'value'}
>>> d.setdefault('key', 'default')
'value'                                          # returns the existing value
>>> d.setdefault('key-doesnt-exist', 'default')
'default'                                        # sets and returns default value
>>> d
{'key-doesnt-exist': 'default', 'key': 'value'}

是否有一个等效的Ruby散列?如果没有,Ruby中的惯用方法是什么?

Is there an equivalent with Ruby hashes? If not, what is the idiomatic approach in Ruby?

推荐答案

Hash可以有默认值或默认的Proc当一个键不存在时调用)。

A Hash can have a default value or a default Proc (which is called when a key is absent).

h = Hash.new("hi")
puts h[123] #=> hi
# change the default:
h.default = "ho"

在上述情况下,哈希值保持为空。

In above case the hash stays empty.

h = Hash.new{|h,k| h[k] = []}
h[123] << "a"
p h # =>{123=>["a"]}

Hash.new([])将不会工作,因为每个键将使用相同的数组(与相同的对象相同)。

Hash.new([]) would not have worked because the same array (same as identical object) would be used for each key.

这篇关于Ruby散列相当于Python dict setdefault的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆