このコードは、存在しないキーがアクセスされたときに返されるデフォルト値を設定します。
この特定のケースでは、与えられたが整数の表現である場合、デフォルトはkey
内で与えられたを返すように設定されています。Array
key
String
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"
ブロック パラメーターの命名について: 最初のパラメーターには好きな名前を付けることができますが、一部の開発者は未使用のブロック operator に名前を付けたいと考えています_
。このようにすると、このパラメーターを気にしないことが一目でわかります。