且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

Ruby散列相当于Python dict setdefault

更新时间:2022-04-17 05:35:03

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.