此代码设置的默认值,当一个不存在的密钥被访问时返回。
在这种特定情况下,如果给定的key
是整数的表示形式,则默认设置为在Array
内返回给定key
。
hash = Hash.new do |_, key|
[key] if /^\d+$/ === key
end
hash["foo"].inspect # => nil
hash[123].inspect # => nil
hash["123"].inspect # => ["123"]
的正则表达式匹配的一些例子:
/^\d+$/ === 123 # => false
/^\d+$/ === "a123" # => false
/^\d+$/ === "123a" # => false
/^\d+$/ === "1.23" # => false
/^\d+$/ === "123" # => true
而对于一个默认值另一个(简单)例如:
hash = Hash.new { |_, key| "this key does not exist" }
hash["foo"] # => "this key does not exist"
hash["foo"] = "bar"
hash["foo"] # => "bar"
关于块参数命名: 你能说出第一个参数是任何你喜欢的,但是一些开发者喜欢命名一个未使用的块运算符_
。乍一看,这种方式很明显,你不关心这个参数。