digメソッドとは
digメソッドは、Rubyのメソッドでありハッシュや配列などのデータ構造に対し、指定したキーまたはインデックスを使用して要素にアクセスできるメソッドです。
使い方
例えば、下記のデータへアクセスする場合には、下記のような方法でデータを取得できます。
data = {
user: {
name: "kaihatu tarou",
address: {
country: "Japan",
region: "aichi"
},
orders: [
{ id: 1, product: "1" },
{ id: 2, product: "2" }
]
}
}
name = data.dig(:user, :name)
# => "kaihatu tarou"
下記のように、他のキーと値が含まれる場合でも、digメソッドを使用することができます。以下のコードでは、item_hash の中にある status_id キーに対応する値の "1 (0から数えた場合)" 番目の値を比較する処理が実行されます。
item_hash = {
"status_id" => [10, 2, 7],
"other_key" => "example",
"more_keys" => [1, 2, 3]
}
item_hash.dig("status_id", 1) == 2
item_hash.dig("status_id", 1000) == 1
# => nil
特徴
digメソッドの特徴としては、存在しない要素にアクセスするとnilが返されることです。
これにより、安全に要素へアクセスできます。
array = [A, B, C]
result = array.dig(5)
# => nil
item_hash = {
"status_id" => [10, 2, 7],
"other_key" => "example",
"more_keys" => [1, 2, 3]
}
item_hash.dig("status_id", 1000) == 1
# => nil